Skip to main content
gamedev.net
🔒 Locked

Creating new events in Lua?

Started by Cactuar Aug 31, 2006 at 6:03 PM 1 replies 950+ views
Original Post
Cactuar
Cactuar
Greetings. I'm working on creating a game engine in C++, with the specific game logic entirely data-driven in Lua. I want to be able to create new types of events in my Lua scripts for my C++ event manager to handle. I figure I could create a Lua table of strings to be hashed as event types easily enough, but what would be the best way to specify event data / function parameters? When the C++ event manager receives an event, it will call the appropriate Lua function for any objects subscribed to that event. I want to be able to fire events in a Lua script, however, and I'm not sure how to handle passing event data to the C++ event manager. So basically I don't want any of my event types hard-coded. When something subscribes to an event in a Lua script, it should create a new event type if it doesn't already exist. Check. The problem is I want to be able to fire an event just as easily by using a string as the event type. I've been trying to think of the best way to pass data along with the event back and forth between C++/Lua but everything I've thought of so far (building a table to pass into the FireEvent function call, etc...) seems unnecessarily complicated. Any ideas? [Edited by - Cactuar on August 31, 2006 7:01:34 PM]
hplus0603
hplus0603
You could use the Lua USERDATA (or lightweight userdata) for events. That's a fancy way of putting C++ objects or void pointers into the Lua world. You can even add methods (table fields) on the userdata members, to make them seem like classes.

I think, in this case, you'd expose the event dispatcher to Lua, as a table. It has at least three methods:

subscribe(eventname, subscriber)
unsubscribe(eventname, subscriber)
sendevent(eventname, params)

The Lua code would then call these methods to manage event delivery, and send events. "Params" would likely be a table containing keyword/value pairs. These would be translated to structs, or whatever else you're using on the C++ side for event parameters. (Hashtable from string to string if you don't want to hard-code the event parameters)

The C++/Lua glue really isn't that much code, and it would probably work reasonably well. Your "subscriber" should probably just be a LUA closure (i e, a bound function, possibly with upvalues).
enum Bool { True, False, FileNotFound };
Cactuar
Cactuar
Thanks. I figured I'd have to do something like that. I wanted to avoid making my scripters build tables/userdata and whatnot to pass into the function but it seems unavoidable.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.