Lua - C API - 运行前创建变量

我想扩展 Lua,使用户在编写脚本时,已经有一个变量可用。这个变量应该是一个自定义类的实例。

为此,我在运行脚本之前在 Lua 栈上使用 lua_newuserdatalua_setglobal(L,"variableName");

问题是它崩溃了,所以我不确定它是否因为我尝试在运行脚本之前创建对象实例或者因为其他地方有其他错误而崩溃。

是否允许在运行 LUA 脚本之前创建对象实例?如果不允许,我有哪些其他方式可以创建最初存在于全局对象中的变量,而无需用户执行任何操作就可以检索到它?

谢谢。

点赞
用户5043289
用户5043289

我想扩展 Lua,这样当用户编写脚本时,一个变量已经对他可用。

这肯定是可能的。一旦 Lua 状态存在,你就可以创建全局变量(即将键/值对放入全局环境表)。

能否在运行 LUA 脚本之前创建对象实例?

是可以的。在我的代码中,我预装了各种东西。有用的表格供终端用户使用。可调用的额外库。

例子代码:

typedef struct { const char* key; int val; } flags_pair;
...
static flags_pair trigger_flags[] =
{
  { "Enabled", 1 },  // enable trigger
  { "OmitFromLog", 2 },  // omit from log file
  { "OmitFromOutput", 4 },  // omit trigger from output
  { "KeepEvaluating", 8 },  // keep evaluating
  { "IgnoreCase", 16 },  // ignore case when matching
  { "RegularExpression", 32 },  // trigger uses regular expression
  { "ExpandVariables", 512 },  // expand variables like @direction
  { "Replace", 1024 },  // replace existing trigger of same name
  { "LowercaseWildcard", 2048 },   // wildcards forced to lower-case
  { "Temporary", 16384 },  // temporary - do not save to world file
  { "OneShot", 32768 },  // if set, trigger only fires once
  { NULL, 0 }
};
...
static int MakeFlagsTable (lua_State *L,
                           const char *name,
                           const flags_pair *arr)
{
  const flags_pair *p;
  lua_newtable(L);
  for(p=arr; p->key != NULL; p++) {
    lua_pushstring(L, p->key);
    lua_pushnumber(L, p->val);
    lua_rawset(L, -3);
  }
  lua_setglobal (L, name);
  return 1;
}
...
  MakeFlagsTable (L, "trigger_flag", trigger_flags)
2016-02-12 01:36:25