如何从堆栈中获取闭包时使用 lua_topointer?

所以,我一直在尝试使用C绑定在nim内实现lua,一切都运行良好,除了我不知道如何处理将lua函数传递给我的nim / c创建的procs / functions。

Lua 代码:

task("custom_task", function()
    task("This is called from lua")
end)

Nim proc:

proc task*(state: lua.Pstate): cint {.cdecl.} =

  var task_name : cstring

  if lua.isstring(state, 1) == 1:
    task_name = lua.tostring(state, cint(1))

  if task_name != nil:
    echo task_name

  # this is triggered for the 2nd parameter
  if lua.isfunction(state, 2) == true:
    var test = lua.topointer(state, 2)

  result = 1

所以,lua api 没有 '到函数' 方法,只有 'tocfunction',所以似乎唯一的方法是使用 topointer 获取该函数,但我无法弄清楚在 nim 中如何使用它。任何帮助都将不胜感激。

点赞
用户2425163
用户2425163

lua_topointer 函数返回的数值只用于哈希或输出/调试功能。 引用Lua manual的内容:

没有将指针转换回原始值的方法。

通常这个函数只用于哈希和调试信息。

因此,如果您想要使用 lua 函数,您将需要找到另一种方法。 我建议将函数存储在 lua 注册表中。 然后可以通过注册表索引和 lua_State 来确定函数。

这种方法的唯一问题是,您必须记住从注册表中移除该函数。 否则它将永远不会被垃圾回收。

或者,可以使用 lua_dump 函数对函数进行转储,但显然这是一种相当昂贵的操作。

2017-10-29 09:21:03