【问题标题】:Lua & implicit global stateLua & 隐式全局状态
【发布时间】:2011-07-07 04:34:53
【问题描述】:

我目前正在将 Lua 集成到我的项目中,并且在途中遇到了一个小设计问题。目前,如果我想从我的主机应用程序中获取信息到 Lua 脚本中,我会调用我在 C 中注册的函数,方式如下:

-- Inside lua
local state = host.get_state()
-- Do something with "state"

现在的问题是:状态显然可以改变,“状态”变量将过时并且很可能无效。到目前为止,我一直忍受着这个,因为不需要太频繁地使用全局状态。在以下情况下问题更大:

local user = host.get_user('id')
host.set_user_flags(user, 'abc')
-- internally "user" is now updated, but to get the accurate information in Lua, I
-- will have to explicitly redo "user = host.get_user('id')" for every operation
-- that accesses this table

我已经阅读了一些关于参考的内容,我认为它们可以帮助我解决这个问题,但我并没有真正理解它。

难道没有办法像我在 C 中那样抛出指针吗?

【问题讨论】:

    标签: c lua embedded-language


    【解决方案1】:

    您在函数内部使用的任何链接都不会更改函数外部的 var。你应该像这样使用 smthg:

    local count
    function MyFunc()
          count = 1
    end
    

    不一定有“本地”。

    作为替代方案,我建议您使用非安全方法:

    count = 0
    function MyFunc(v) --we will throw varname as a string inside
         _G[v] = 1 -- _G is a global environment
    end
    MyFunc('count')
    print(count)
    

    【讨论】:

    • 函数是用C定义的,刚刚注册到Lua,我需要一个Lua C API方法来做这个
    • 那么,请查看 Lua 参考手册中的 lua_setlocal 和 lua_getlocal C 函数。
    【解决方案2】:

    我发现表是作为引用传递的,我可以像这样从函数内部修改它们:

    static int dostuff(lua_State *L)
    {
        lua_pushstring(L, "b");
        lua_pushnumber(L, 23);
        lua_settable(L, 1);
    
        return 0;
    }
    /* lua_register(L, "dostuff", &dostuff); */
    

    在 Lua 内部:

    t = { a = 'a', b = 2 }
    
    print(t.a, t.b)
    dostuff(t)
    print(t.a, t.b)
    

    将导致:

    a   2
    a   23
    

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      相关资源
      最近更新 更多