Advertisement

Add function to luabind object(table)

Started by July 11, 2004 12:02 PM
1 comment, last by Krun 20 years, 4 months ago
Hi! In luabind's documentation there is the following example to show how to assign data to a lua table using a object: void my_function(const object& table) { if (table.type() == LUA_TTABLE) { table["time"] = std::clock(); table["name"] = std::rand() < 500 ? "unusual" : "usual"; } } Now, how would one assing a C++ function to a member in a table using the above method? (the example shows only numbers and strings)
Say you bound some functions to Lua earlier using a statement like

void func1() { cout << "blah" << endl; }void donothing() { }void foo() { cout << "bar" << endl; }module(L) [    def("func1",&func1),    def("donothing",&donothing)    def("foo",&foo)];// then your function that assigns values to the table could// look like this:void my_function(const object& table){    if (table.type() == LUA_TTABLE)    {        string funcName;        if ( someValue )            funcName = "func1";        else if ( someOtherValue )            funcName = "donothing";        else            funcName = "foo";        // actually assign the function to the table        table["myFunction"] = luabind::get_globals(L)[funcName];                  }}


But honestly this whole late-binding stuff almost seems like it should be done fully on the scripting side of things.
Advertisement
I would need late-binding because of the system I use for creating entitis in my engine. Eg. how to create a GUI window:

-- the game engine calls the Init() function automaticly
function Init()
win = {}
win.Position = { X=50,Y=100 }
win.Size = { X=100,Y=80 }
win.Title = "Example window"
win.OnClose = OnCloseWindow

Game.UI.Create(win)

win.SetTitle("New title") -- want to be able to do this
end

function OnCloseWindow()
print("Window was closed")
win = nil
end

The Game.UI.Create function is a export from the engine. It takes a luabind::object as a arg. and creates a UI window from the given params in the table. Now, it would like to give Lua code access to window functions like SetTitle or SetPosition after the window is created. This would be with code something like this:

void CreateWindow(const object& table){CWindow* win = new CWindow();// set the window parameters from the passed table// this is the important part, here we give the script access// to the set title function so the script can change the title// after the window is created, I have everything working up to heretable["SetTitle"] = win->SetTitle;m_Windows.Add(win);}

This topic is closed to new replies.

Advertisement