如何在lua中创建命名空间?

cod*_*nia 10 lua

我想将静态类函数绑定到lua.如您所知,静态类函数与类函数有所不同.所以lua中的函数调用代码应该是这样的......


//C++
lua_tinker::def(L, "Foo_Func", &Foo::Func);

//Lua
Foo_Func()
Run Code Online (Sandbox Code Playgroud)

但我想像这样在lua中调用函数


//Lua
Foo.Func()
Run Code Online (Sandbox Code Playgroud)

有没有办法像这样使用?Lua表可能会有所帮助.但我找不到任何参考资料.

Jud*_*den 11

是的,这将通过表来完成,实际上是大多数模块在导入它们时的工作方式require.

Foo = {} -- make a table called 'Foo'
Foo.Func = function() -- create a 'Func' function in stored in the table
    print 'foo' -- do something
end
Foo.Func() -- call the function
Run Code Online (Sandbox Code Playgroud)

  • 请记住,如果您声明了以下内容:Foo.Func = function(this)... end您可以调用它:Foo:Func()(请注意':'),这也将Foo表作为第一个函数参数传递。 (2认同)