为嵌入式Lua脚本设置“环境” [英] Setting up an 'environment' for an embedded Lua Script
问题描述
我在一个C ++应用程序中嵌入了一个Lua解释器。
I am embedding a Lua interpreter in a C++ application.
我想为运行脚本设置一个环境,使某些变量脚本。
I want to setup an 'environment' for running scripts, such that certain variables are made available to all scripts.
例如,我想将READ ONLY对象Foo和FooBar暴露给脚本,以便Foo和FooBar可用于所有正在运行的脚本。
For example, I want to expose READ ONLY objects Foo and FooBar to scripts, such that Foo and FooBar are available to all running scripts.
有谁知道我该怎么做?
Does anyone know how I can do this?. A snippet to show how to so this would be very useful.
推荐答案
我没有听说过Lua中的只读变量但是你可以通过调用一个函数调用来阻止修改。
I haven't heard of read-only variables in Lua but you can prevent modification by making the environment available via a function call instead.
如果C ++应用程序很大,你可能需要使用一个工具生成一个接口你可以从Lua打电话。我过去用了tolua ++运气:
If the C++ application is large, you will probably want to use a tool to generate an interface you can call from Lua. I have used tolua++ in the past with some luck:
假设 demo.hpp
是C ++的头文件应用程序:
Suppose demo.hpp
is a header file of the C++ application:
#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调用的内容:
demo.pkg
lists the things that should be callable from Lua:
$#include "demo.hpp"
namespace demo
{
class Foo
{
double getX() const;
};
Foo* getFoo();
}
生成 demo_stub.cpp
和 demo_stub.hpp
包含我们的Lua模块的文件:
Generate demo_stub.cpp
and demo_stub.hpp
files containing our Lua module:
$ tolua++5.1 -o demo_stub.cpp -H demo_stub.hpp demo.pkg
main.cpp
是一个Lua解释器,它加载 demo
模块:
main.cpp
is a Lua interpreter that loads the demo
module:
#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
中声明。
The tolua_demo_open()
function was generated by tolua++ and is declared in demo_stub.hpp
.
创建一个名为 demo
:
$ g++ -I/usr/include/lua5.1 demo.cpp demo_stub.cpp main.cpp -ltolua++5.1 -llua5.1 -o demo
demo.lua
脚本
print("Hello, world!")
print(tolua.type(demo.getFoo()))
print(demo.getFoo():getX())
并将脚本提供给解释器:
and feed the script to the interpreter:
$ ./demo < demo.lua
Hello, world!
demo::Foo
42
这篇关于为嵌入式Lua脚本设置“环境”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!