Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm using Irrlicht(C++) for a 3D engine, and it has a built in GUI system. The GUI events are something like this:

switch(eventtype)
case button_pressed:
    stuff
case editbox_edited:
    stuff

So far I have begun writing a system that allows me to create the GUIs with Lua scripts. It was very easy to make it so it creates the GUI controls from Lua, but I can not think of a good way to define what should happen when control events occur from Lua too. Here's an example of what I have so far:

Lua:

local button = create_button("button label",10,10,100,50)
toggle_control(button,false)

C++:

static int CreateButton(lua_State* L)
{
 int n = lua_gettop(L);
 core::stringw label = lua_tostring(L,1);
 core::stringw tt((n>=5?lua_tostring(L,6):""));
 int x = lua_tonumber(L,2);
 int y = lua_tonumber(L,3);
 int w = lua_tonumber(L,4);
 int h = lua_tonumber(L,5);
 core::rect r(x,y,x+w,y+h);
 unsigned int id = NextID();
 if(r.isValid())
 {
  gui::IGUIButton* b = device->getGUIEnvironment()->addButton(r,0,0,label.c_str(),tt.c_str());
  cl.insert(ControlPair(id,b));
  lua_pushnumber(L,id);
 }
 else
  lua_pushnumber(L,-1);
 return 1;
}

Please ignore the security issues with the code (it is a very early version). So my question is this: What are some good ways of defining the control events from a script interpreter in C++?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

I'm not familiar with Irrlicht, but you could pass a function to the CreateButton that should get called on an event that deals with that button. You could either pass a string, and do a lookup in the global table for a function with that name at run time, or store a pointer to the lua function itself (which should allow you to do lambdas).

In the past I've done a convention-over-configuation thing, where the game automatically picks up lua functions that fit a callback style. Eg:

createButton("myButton", "label text", 10, 10, 100, 50)

...

function onEvent_myButton(eventParams)
    -- process event
end

The game parses the global table, looking for onEvent functions and parsing the function name to see if it matches your new button name. It hooks that up as a callback.

For some reason our designers found this a more friendly approach.

share|improve this answer
    
I've implemented this and I like it. Thanks! –  BarakatX2 Aug 25 '10 at 7:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.