Lua-icxx was designed that so that it can be used in conjunction with SWIG, but it does not support getting and putting SWIG-exported instances. Goal is to support Foo* foo = lua.getGlobal("foo")
and lua.setGlobal("foo", foo)
where "foo" in Lua is assumed to be of C++ class Foo
exported to Lua as Lua "class" Foo, and foo in C++ is assumed to be of class Foo
.
For getting an object out of Lua (first case), would get "foo" from the Lua interpreter, then get the object's type name string (this is in the object, as per "26.7.2 Userdata and Metatables"). Then, find the swig_type_info
using SWIGTypeQuery
with that name. Finally, call SWIG_ConvertPtr
to get a void*
to the Foo
, and reinterpret_cast<Foo*>
. See http://lua-users.org/lists/lua-l/2011-04/msg00595.html, as well as "26.5.2 SWIG's Lua-C API" on swig.org, and http://www.swig.org/Doc2.0/SWIGDocumentation.html#Modules_external_run_time.
For pushing to Lua, would need to get a string name for the C++ type ("Foo"), most likely via a C++ preprocessor macro in a templatized setGlobal<T>(string luaObjName, T& cppObj)
. Then SWIGTypeQuery
on the name, and SWIG_NewPointObj
with own=false on the object. Since foo is now on the Lua stack, then set the global via usual Lua C API call.
There should be no need for user of lua-icxx to link to the SWIG-generated DLL exporting Foo, the type info is apparently shared via the Lua interpreter, plus Foo header is already included in C++ otherwise foo could not exist.
The one tricky aspect might be the header file that must be generated by SWIG, declaring and defining the SWIG_*
functions mentioned above. The type info is apparently shared via a table in the Lua interpreter, and modules that need to share type info (say, because one module's class derives from class in another module) just need to use the same table, via the -DSWIG_TYPE_TABLE=name
. This suggests that the Lua tables containing the type info are globals referenced by given name, in which case they can be specified as a text string during Lua-icxx initialization: lua.useSwigTypeTable("name1")
would tell lua-icxx to look in the type info table referenced by global "name1" whenever type infos are needed. This header file would be generated once by us, generalized to make the typeinfo table name a call parameter, and compile into lua-icxx. Then user never needs to generate the header, one less step to worry about.
If more than one type table is used (some modules share one set of types, and a separate set of modules -- no intersection -- shares another set of types), each table will be searched, and the first one that has a type name of interest will be used. If multiple modules define the same type name, there could be problems, so perhaps there should be a way of telling lua-icxx which type table to use. This would be straightforward for getGlobal
and setGlobal
but other lua-icxx functions may be less so. Given how rare this situation would likely be, it may not be worth worrying about.
Diff: