user5370661
user5370661

Reputation:

LuaBridge running C++ main function in lua for Love2D

Here is my C++ main function :

int main() {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
getGlobalNamespace(L).
        beginNamespace("o").
            beginClass<Object>("Object").
                addConstructor<void (*) (double, double)>().
                addProperty("width", &Object::getWidth, &Object::setWidth).
                addProperty("height", &Object::getHeight, &Object::setHeight).
                addProperty("x", &Object::getX, &Object::setX).
                addProperty("y", &Object::getY, &Object::setY).
            endClass().
        endNamespace();
lua_pcall(L, 0, 0, 0);
luaL_dofile(L, "main.lua");}

And here is my main.lua for Love2D

function love.load()
   obj = o.Object(10, 20) end

When i tried to run it with love it says that obj is a nil value and i realized that Love2D doesn't run my main function in C++ to create the object class. How do i call a C++ main function in Lua using LuaBridge?

Upvotes: 0

Views: 621

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473946

What you are doing is using two separate programs: the one you build with your "main function", and the actual Love2D executable. They're separate executables; they have no more relation to one another than lua.exe has to python.exe.

What you appear to be wanting to do is write a C++ library that is used by Love2D. You can do that, but it requires that you write, not a C++ program, but a dynamic library. You have to write a Lua C-module.

How you write a dynamic library depends on your platform of choice. But that dynamic library must export the appropriate functions, as detailed in the Lua 5.1 documentation. If your C module is named "test", then it must export a function called luaopen_test.

The job of this function is essentially what your main does. Your luaopen_ function does not have to create a Lua state; it will be given one. It's job is to return a table that contains the functions and APIs you want to export in your module. So it registers everything with Lua as needed.

Your main puts its stuff in the global "namespace", but this is generally considered quite rude. It's better to build a local table and put your stuff there, returning the table as the return value. I'm not familiar with LuaBridge's API, so I have no idea how to go about doing that.

Worst case is that you could build a global table as you currently do, but after building it, load it into a local table, clear the global entry, then return the table.

Upvotes: 0

Related Questions