🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Simple binding of functions to C++

Started by
2 comments, last by vstrakh 7 years, 3 months ago

I was using LUA like 15 years ago :) So, well, I have forgotten how it worked :) Also I have forgotten how exactly it was called what I want to make so I have trouble googling it.

I need a very simple thing only, a lua script that calls my C++ functions. I recall you were initailizing lua, then specified which lua script to parse (filename) and then define "binding" or was it "registering" a function?

I don't need other fancy stuff, only this.

EDIT: It seems the function I used in the past was lua_register which was deprecated and now you use some "table" thing? Below is a code that compiles but has no effect (luaPrint not working):


int luaPrint(lua_State *L)
{

	tPrint("%s\n", lua_tostring(L, -1));
}

int testLua()
{
    lua_State *L = luaL_newstate();

    luaL_Reg Regs[] =
    {
        { "print", luaPrint },
        { NULL, NULL }
	};

    lua_newtable(L);
    luaL_setfuncs(L,Regs,0);
    lua_pushvalue(L,-1);

    if(luaL_dofile(L, "test.lua"))
    {
        tPrint("Error:%s\n", lua_tostring(L, -1));
    }

  lua_close(L);
  return 0;
}

Stellar Monarch (4X, turn based, released): GDN forum topic - Twitter - Facebook - YouTube

Advertisement

Check out Selene, it's very easy to set up and use.

Check out Selene, it's very easy to set up and use.

Can't it be done with pure lua? I recall it was a very trivial thing, just a few lines of code...

Stellar Monarch (4X, turn based, released): GDN forum topic - Twitter - Facebook - YouTube

I recall it was a very trivial thing, just a few lines of code...

A good start to refresh memory is to read PIL. First edition is free on Lua site: https://www.lua.org/pil/contents.html

Below is a code that compiles but has no effect (luaPrint not working):

New luaL_setfuncs will register functions in a table that you create. It won't appear in Lua global environment by itself. You'll have to store it in global variable to be accessible on Lua side.

But probably you don't need that at all. Since lua_register is a macro, and it still there in Lua 5.2, 5.3. Use that if you need few functions to be registered at global scope.

This topic is closed to new replies.

Advertisement