2
votes

Is it possible to only call one specific function in a Lua script from C. Currently, I have a Lua script which calls a C function. Now, I need this C function to call just one Lua function from the mentioned script.

EDIT: The C functions look like this:

#include <lua.h>
#include <lauxlib.h> 
#include <lualib.h>


static double E1(double x) {

    double xint = x;
    double z;


    lua_State *L;
    L = luaL_newstate();

    luaL_openlibs(L);

    luaL_loadfile(L, "luascript.lua");

    lua_pcall(L, 0, 0, 0);

    lua_getglobal(L, "func");
    lua_pushnumber(L, x);

    lua_pcall(L, 1, 1, 0);

    z = lua_tonumber(L, -1);
    lua_pop(L, 1);

    lua_close(L);

    return z;
}

static int Ret(lua_State *L){

    double y = lua_tonumber(L, -1);

    lua_pushnumber(L, E1(y));

    return 1;
}

int luaopen_func2lua(lua_State *L){
    lua_register(
                    L,
                    "Ret",
                    Ret
                    );
    return 0;
}

The Lua script looks like this:

 require "func2lua"

 function func (x)
     -- some mathematical stuff
     return value
 end

 x = 23.1

 print(Ret(x)) -- Ret is the C function from the top c-file
1
Can't you write this lua function in C? Usually it is lua that calls C not other way around - 4pie0
Unfortunately, a third program depends on Lua. So, for me, there is no way around it. - 7143ekos
Perhaps some interpretation of the Lua file will help. When you execute the Lua file it: 1) loads and runs func2lua.lua, sets the global func to a function value, sets the global x to a number, invokes the value of the global Ret variable as a function and invokes the value of the global print variable as a function. Until func is set, its value will be nil. It's unclear who you want whom to call and when. You probably don't want to load and execute the file more than once. - Tom Blodget

1 Answers

1
votes

Yes you can. C function will need a way to get that function. Depending on your requirements you can either pass that Lua function to C function as one of arguments, or store that Lua function where C can reach it - either in global environment (then C will lua_getglobal() that function), or in some predefined table, belonging to that script.