4

Given a lua file like

-- foo.lua
return function (i)
  return i
end

How can I load this file with the C API and call the returned function? I just need function calls beginning with luaL_loadfile/luaL_dostring.

Sebastian Graf
  • 3,602
  • 3
  • 27
  • 38

1 Answers1

3

A loaded chunk is just a regular function. Loading the module from C can be thought of like this:

return (function()  -- this is the chunk compiled by load

    -- foo.lua
    return function (i)
      return i
    end

end)()  -- executed with call/pcall

All you have to do is load the chunk and call it, its return value is your function:

// load the chunk
if (luaL_loadstring(L, script)) {
    return luaL_error(L, "Error loading script: %s", lua_tostring(L, -1));
}

// call the chunk (function will be on top of the stack)
if (lua_pcall(L, 0, 1, 0)) {
    return luaL_error(L, "Error running chunk: %s", lua_tostring(L, -1));
}

// call the function
lua_pushinteger(L, 42); // function arg (i)
if (lua_pcall(L, 1, 1, 0)) {
    return luaL_error(L, "Error calling function: %s", lua_tostring(L, -1));
}
Adam
  • 3,053
  • 2
  • 26
  • 29
  • Ahh, thanks, that's a really helpful semantic of 'chunk'. Actually, one of the versions I've tried so far was similar, only that I my first call was `lua_pcall(L, 0, 0)`, which discarded the result. That left me wondering why there was no return value. – Sebastian Graf Aug 30 '16 at 22:34