Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make namespace in lua?

Tags:

lua

I want to bind static class function to lua. As you know, static class function is something difference with class function. So function call code in lua should be like this...


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

//Lua
Foo_Func()

But I want to call function in lua like this


//Lua
Foo.Func()

Is there any way to use like that? Lua table might be helpful. But I cannot find any references.

like image 592
codevania Avatar asked Dec 09 '10 02:12

codevania


People also ask

What is unpack Lua?

In Lua, if you want to call a variable function f with variable arguments in an array a , you simply write f(unpack(a)) The call to unpack returns all values in a , which become the arguments to f .

How does require work in Lua?

Lua offers a higher-level function to load and run libraries, called require . Roughly, require does the same job as dofile , but with two important differences. First, require searches for the file in a path; second, require controls whether a file has already been run to avoid duplicating the work.

What is a Lua module?

A module in the Lua programming language is a piece of code that contains functions and variables: it's an user library. It's a powerful way to split your code in several files. A module is loaded using the Lua require keyword.

What does function mean in Lua?

It means that, in Lua, a function is a value with the same rights as conventional values like numbers and strings. Functions can be stored in variables (both global and local) and in tables, can be passed as arguments, and can be returned by other functions.


2 Answers

Yes, that would be done with a table and is in fact how most modules work when you import them with 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
like image 158
Judge Maygarden Avatar answered Jan 02 '23 23:01

Judge Maygarden


I think you'll find PiL chapter 26.2 most interesting. If you compile your library to the same name as the table (so filename == modulename) then you can simply require() the module.

like image 20
jpjacobs Avatar answered Jan 02 '23 22:01

jpjacobs