Lua and Javascript (specifically spidermonkey) are two languages which were specifically designed for embedding in a C or C++ application.
The general order of operations for using one of these languages is:
Lua is supported by SWIG, which saves you a lot of work. SWIG generates a method called SWIG_init which accomplishes step #2. It also generates methods SWIG_NewPointerObj and SWIG_ConvertPtr which help you with items #3 & #6 respectively.
In pratice, a simple implementation of this from the Crate Game Engine looks like:
lua_State *l = lua_open(); luaL_reg lualibs[] = { {"base", luaopen_base}, {"table", luaopen_table}, /* {"io", luaopen_io}, */ {"string", luaopen_string}, {"math", luaopen_math}, {"debug", luaopen_debug}, /*{"loadlib", luaopen_loadlib}, */ /* add your libraries here */ {SWIG_name, SWIG_init}, {NULL, NULL} }; for(int i=0; lualibs[i].func != 0 ; i++) { lualibs[i].func(l); /* open library */ lua_settop(l, 0); /* discard any results */ } SWIG_NewPointerObj(l, mWorld, SWIGTYPE_p_CGE__World, false); lua_setglobal(l, "mWorld"); SWIG_NewPointerObj(l, mSystem, SWIGTYPE_p_CGE__System, false); lua_setglobal(l, "mSystem"); SWIG_NewPointerObj(l, useWithObject, SWIGTYPE_p_CGE__Object, false); lua_setglobal(l, "useWithObject"); SWIG_NewPointerObj(l, parentObject, SWIGTYPE_p_CGE__Object, false); lua_setglobal(l, "parentObject"); int result = luaL_loadbuffer(l, mScript.c_str(), mScript.length(), "script"); if (result == 0) { if (lua_pcall(l, 0, 0, 0) != 0) { //Handle Error } } else if (result == LUA_ERRSYNTAX) { //Handle Error } else if (result == LUA_ERRMEM) { //Handle Error } lua_close(l);
Javascript is not supported by SWIG and would require much more code to accomplish the same work.
Recent comments
16 hours 24 min ago
21 hours 28 min ago
21 hours 57 min ago
1 day 14 hours ago
1 day 21 hours ago
1 week 6 days ago
3 weeks 15 hours ago
3 weeks 1 day ago
3 weeks 3 days ago
3 weeks 4 days ago