5

A very basic question i guess:

The C++ code, calling lua looks like this:

lua_State* m_L;
m_L = lua_open();
luabind::open(m_L);
luaL_dofile(m_L, "test.lua");
try {
    luabind::call_function<void>(m_L, "main");
} catch (luabind::error& e) {
    std::string error = lua_tostring(e.state(), -1);
    std::cout << error << std::endl;
}
lua_close(m_L);

now test.lua has the following contents:

function main()
print "1"
end

Upon execution I receive the error:

test.lua:2: attempt to call global 'print' (a nil value)

What is the problem? It has something to do with environments? I thought functions like print are defined in the global environment. Why is it not found then?

Thank you very much.

chris.schuette
  • 307
  • 2
  • 11
  • ok i figured it out: luaopen_base(m_L); needs to be called after lua_open() – chris.schuette Feb 24 '12 at 13:17
  • you'll need to call luaopen_string(m_L), luaopen_math(m_L), etc to open the appropriate built in lua libraries, if you plan on using those as well. – Mike Corcoran Feb 24 '12 at 15:41
  • @chris.schuette: You should either answer your own question and accept that answer (thus marking the question as being finished) or delete the question. – Nicol Bolas Feb 24 '12 at 16:48
  • 1
    @NicolBolas I don't think I can answer my own questions yet - I think my reputation is too low. Do you think it would be appropriate to delete this question? Maybe someone will find this info here valuable... – chris.schuette Feb 24 '12 at 21:29

1 Answers1

6

As you figured it out, you have to call luaopen_base to get print and other base functions. Then you need to call luaopen_string, luaopen_math, to get the basic modules and functions in. Instead of writing it all out manually, can load all Lua base function at once with luaL_openlibs:

lua_State* m_L = luaL_newstate();
luaL_openlibs(m_L);
Michal Kottman
  • 16,375
  • 3
  • 47
  • 62