lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


In my application, I embed Lua and I want to allow users to specify a
Lua function by name. If the name is a global, this is easy -

lua_pushstring(L, name)
lua_gettable(L, LUA_GLOBALSINDEX)

But this doesn't work if the user enters a name like os.date. I could
go to the other extreme:

lua_pushliteral(L, "return (");
lua_pushstring(L, name);
lua_pushliteral(L, ")");
lua_concat(L, 3);
code = lua_tostring(L, -1);
top = lua_gettop(L);
if (!luaL_dostring(L, code))
  lua_error(L);
/* Sanity check */
if (lua_gettop(L) != top+1 || !lua_isfunction(L, -1))
  luaL_error(L, "'%s' is not a function");

but that seems like a lot of work. Also, I'm not really sure I need
fully general expressions - the only real use I have is for dotted
names.

Is there a simpler way that I have missed? Having said that, I use
similar code in a couple of places, so maybe I should just capture
this as a utility function eval_expr(L, expr).

Paul.