Sebastian Graf
Sebastian Graf

Reputation: 3740

Call a function returned by a lua script from C

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.

Upvotes: 4

Views: 1050

Answers (1)

Adam
Adam

Reputation: 3103

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));
}

Upvotes: 3

Related Questions