7143ekos
7143ekos

Reputation: 23

Call only one specific function in a Lua script from c

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

Upvotes: 2

Views: 1535

Answers (1)

Vlad
Vlad

Reputation: 5847

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.

Upvotes: 1

Related Questions