Asaf Nudler
Asaf Nudler

Reputation: 43

Initializing Lua state in C

I'm trying to use Lua (5.2) from my C code. I'm creating a Lua state and calling "luaL_openlibs", but global function such as "loadstring" aren't initialized.

lua_State* L = luaL_newstate();
luaL_openlibs(L);
luaL_loadstring(L, "print(loadstring)");
lua_pcall(L, 0, LUA_MULTRET, 0);

Result is: nil. Simple Lua code works (for example, print("hello")), so does the standard libs (strings, ...). Please help me to figure out what am I doing wrong, i've been searching google for a couple of hours and all I found were those weird old mail-lists and Lua documentation (which is also not very helpful, IMO).

Thanks.

Upvotes: 2

Views: 1402

Answers (2)

Oliver
Oliver

Reputation: 29611

The reference manual is always very useful. As you can see in the table at the bottom, there is no loadstring in Lua 5.2, the closest is load. Also if you check section 8.2 of that manual, Changes in the Libraries, you can see an item regarding loadstring that was available in 5.1, saying incidentally that loadstring has been replaced by load, same functionality.

Changing the source should always be a last resort ie only if there is no other way. Here, what you want is easily doable via the C API:

lua_getglobal(L, "load")
lua_setglobal(L, "loadstring")

Even in cases where you don't use C (just straight Lua), you can do loadstring = load at the top of the script. Or setenv LUA_INIT "loadstring=load" in a console or .bashrc, then Lua executes this for every script it runs (from that console). Or run your script as lua -e'loadstring=load' yourScript.lua. Am I missing any? :)

Upvotes: 1

Asaf Nudler
Asaf Nudler

Reputation: 43

Ok, found this in the comments:

@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base
** library. You can rewrite 'loadstring(s)' as 'load(s)'.

So after defining that const I could use "loadstring" :)

Upvotes: 1

Related Questions