Call a function returned by a lua script from C

Sebastian Graf

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.

Adam

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

call Lua function from C++ conditionally

How to get returned table from Lua function in C++?

c - using a pointer returned from function in a function call

Call Lua table function from C++ w/ self in function

Unable to call a C function from Lua-lanes

Call Lua function from C++ using LuaBridge

How to listen to specific function call in Lua from C++?

How to safely call a C++ function from Lua

Calling C++ class function from LUA script

passing Lua script from C++ to Lua

Simplify Lua function call to C function

Lua call function from string on self?

How to call a function from moonscript in lua?

Shell script not executing a command returned from a function

Shell script : Count returned from function is not correct

How to get multiple returned tables from Lua function?

lua synchronous call C asynchronous function

Lua C function call returns nil

lua, call script from C with limited modules, error on string.len

How to call & await async C# method from Lua / MoonSharp script?

Use object returned by Lua script

Is it safe to call c_str() directly on returned std::string from a function?

How to construct a named list (a SEXP) to be returned from the C function called with .Call()?

Call a script function from another function

Managing objects returned from C++ function

Calling C function from returned pointer in NodeJS

Is it safe to assume free() on string(char *) returned from a function call?

Call function when new result has been returned from API

Meteor.call returns undefined when returned from _.wrapAsync function