Jump to content

Guppy's Blog

  • entry
    1
  • comments
    0
  • views
    4,253

Pushing complex lua tables from C++


Guppy

2,685 views

 Share

While having a small set of fairly simple tables you could properly get away with using

 

Leadwerks::Interpreter::NewTable();
size_t top=Leadwerks::Interpreter::GetStackSize();

Leadwerks::Interpreter::PushString("Key1");
Leadwerks::Interpreter::PushString("Value1");
Leadwerks::Interpreter::SetTable(top);

Leadwerks::Interpreter::PushString("Key2");
Leadwerks::Interpreter::PushInt(5);
Leadwerks::Interpreter::SetTable(top);

(ect)

 

But it's really rather bothersome and hard to read and maintain.

 

And it doesn't get easier when you have somewhat complex like the event table for the gui I'm working on;

 

{
event = "onChanged",
value = 25.7,
caption = "label",
widget = {
numChildren = 0,
parent = "parentWidget",
properties = {
enabled = true,
captoion = "label",
visible = "true",
class = "ScrollBar",
}.
id = "testScrollBar",
children {
},
doStuff: [function]
}

}

 

Just imagine having to push that to lua using the above technique!

 

Weather or not you think what I've come up with is easier to use/read/maintain is a matter of taste so I'll give you a preview;


using namespace luaHelper;

typeMap widgetBaseinfo={
{"id", new luaString(widget->getName()) },
{"parent", new luaString(widget->getParent() == nullptr? "": widget->getParent()->getName()) },
{"numChildren", new luaInt(widget->getChildCount()) },
{"UserStrings", new stringTable(widget->getUserStrings()) }
};

typeMap properties={
{"visible", new luaBool(widget->getVisible()) },
{"class", new luaString(widget->getTypeName()) },
{"enabled", new luaBool(widget->getEnabled()) }
};

widgetBaseinfo["properties"]=new luaTable(properties);

typeMap event={
{"event", new luaString(eventType) },
{"widget" ,new luaTable(widgetBaseinfo) },
{"value", value },
}

luaTable *table=new luaTable(event);
table->push();

delete table;

 

The above is more or less the code I use now ( except I generate widgetBaseinfo, properties and event in different member functions )

 

if you like this way of working you can download the helper file here, and (ab)use it anyway you like

http://decoder.dk/LE/lua_tablehelper.h

 

( aparently you cannot attach files in blog posts? )

 

 

Let me know what you think.

 

I've been considering letting table::push automatically delete it self since I always seem to do that anyway - and it would save me some worries about memory leaks from forgetting to delete.

  • Upvote 3
 Share

0 Comments


Recommended Comments

There are no comments to display.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...