Call the function returned by lua script from C

Given a lua file e.g.

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

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

+4
source share
1 answer

A loaded chunk is a normal feature. Loading a module from C can be represented as follows:

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 piece and call it, its return value will be 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));
}
+3
source

Source: https://habr.com/ru/post/1653037/


All Articles