【问题标题】:Lua - C API - Create variables before runningLua - C API - 在运行前创建变量
【发布时间】:2016-05-20 15:41:17
【问题描述】:

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

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

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

是否允许在运行 LUA 脚本之前创建对象实例?如果没有,我还有什么其他方法可以创建一个最初存在于全局变量中的变量,而用户不必做任何事情来检索它?

谢谢。

【问题讨论】:

  • 您在添加变量之前是否创建了新的lua_State
  • 实际上并没有“运行 Lua 脚本”的概念。您创建一个状态,然后将一个函数压入堆栈(例如使用lua_load),然后调用该函数。 Lua 执行由主机驱动。没有您可能期望从其他语言中获得的“运行机器”。
  • 是的,我有(使用 luaL_newstate())。您的评论也让我意识到在运行脚本之前我必须正确地创建一个全局变量。就像在这个例子中(lua-users.org/wiki/UserDataExample)所以我必须有另一个错误。 lua_newuserdata调用luaC_checkGC时发生的崩溃
  • @KerrekSB 实际上我只是传递了一个 NULL 指针而不是堆栈...抱歉浪费时间...我会关闭这个问题。
  • 是的,我有点料到会是这样。删除。

标签: c lua


【解决方案1】:

我想扩展 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)

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多