Setting the "environment" for the built-in Lua Script

I embed a Lua interpreter in a C ++ application.

I want to set up an “environment” for running scripts, so that some variables become available for all scripts.

For example, I want to set READ ONLY objects only for Foo and FooBar, so that Foo and FooBar are available for all running scripts.

Does anyone know how I can do this? A fragment to show how this would be very useful.

+3
source share
2 answers

I have not heard of read-only variables in Lua, but you can prevent them from being modified by making the environment accessible through a function call.

++ , , , , Lua. tolua ++ :

, demo.hpp - ++:

#ifndef SO_DEMO_HPP
#define SO_DEMO_HPP

namespace demo
{
    class Foo
    {
        double x;

    public:
        Foo(double x) : x(x) {}
        double getX() const { return x; }
    };

    Foo* getFoo();
}

#endif

demo::getFoo() demo.cpp.

demo.pkg , Lua:

$#include "demo.hpp"

namespace demo
{
    class Foo
    {
        double getX() const;
    };

    Foo* getFoo();
}

demo_stub.cpp demo_stub.hpp , Lua:

$ tolua++5.1 -o demo_stub.cpp -H demo_stub.hpp demo.pkg

main.cpp - Lua, demo:

#include "demo.hpp"

extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <tolua++.h>
}
#include "demo_stub.hpp"

int main()
{
    lua_State *L = lua_open();

    luaL_openlibs(L);
    tolua_demo_open(L);

    if (luaL_dofile(L, NULL) != 0)
        fprintf(stderr, "%s\n", lua_tostring(L, -1));

    lua_close(L);
    return 0;
}

tolua_demo_open() tolua ++ ​​ demo_stub.hpp.

Lua demo:

$ g++ -I/usr/include/lua5.1 demo.cpp demo_stub.cpp main.cpp -ltolua++5.1 -llua5.1 -o demo

a demo.lua script

print("Hello, world!")
print(tolua.type(demo.getFoo()))
print(demo.getFoo():getX())

script :

$ ./demo < demo.lua
Hello, world!
demo::Foo
42
+1

lua_setglobal.

" ", , Foo (, Foo = 10) Foo reverse (, Foo.x = 10)?

0

Source: https://habr.com/ru/post/1781100/


All Articles