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.

1 Answer 1

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.