Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Call C function in Lua (lua-5.2.3)


May 12, 2021 Lua



Lua's ability to call C functions will greatly improve Lua's scalability and availability.

For some operating system-related functions, or for more efficient modules, we can do this entirely through the C function, and then call the specified C function through Lua.

For C functions that can be called by Lua, the interface must follow the form required by Lua, i.e. typedef int (lua_CFunction) (lua_State L).

To put it simply, the function type contains only a pointer representing the Lua environment as its unique argument, which allows the implementer to further obtain the actual incoming arguments in Lua's code. T he return value is integer, which means that the C function will return the number of return values to the Lua code, or, if not, return 0. It should be noted that the C function cannot return the true return value directly to the Lua code, but instead passes the call parameters and return values between the Lua code and the C function through a virtual stack.

Instance code:

// testlua.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <math.h>

extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}

//待Lua调用的C注册函数
static int add2(lua_State* L)
{
    //检查栈中的参数是否合法,1表示Lua调用时的第一个参数(从左到右),依此类推。
    //如果Lua代码在调用时传递的参数不为number,该函数将报错并终止程序的执行。
    double op1 = luaL_checknumber(L,1);
    double op2 = luaL_checknumber(L,2);
    //将函数的结果压入栈中。如果有多个返回值,可以在这里多次压入栈中。
    lua_pushnumber(L,op1 + op2);
    //返回值用于提示该C函数的返回值数量,即压入栈中的返回值数量。
    return 1;
}

//待Lua调用的C注册函数。
static int sub2(lua_State* L)
{
    double op1 = luaL_checknumber(L,1);
    double op2 = luaL_checknumber(L,2);
    lua_pushnumber(L,op1 - op2);
    return 1;
}

//待Lua调用的C注册函数。
static int l_sin (lua_State *L) {
    double d = lua_tonumber(L, 1); /* get argument */
    lua_pushnumber(L, sin(d)); /* push result */
    return 1; /* number of results */
}

int _tmain(int argc, _TCHAR* argv[])
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    //将指定的函数注册为Lua的全局函数变量,其中第一个字符串参数为Lua代码
    //在调用C函数时使用的全局函数名,第二个参数为实际C函数的指针。
    lua_register(L, "add2", add2);
    lua_register(L, "sub2", sub2);
    lua_register(L, "l_sin", l_sin);
    //在注册完所有的C函数之后,即可在Lua的代码块中使用这些已经注册的C函数了。
    luaL_dofile(L,"test.lua");

    //if (luaL_dostring(L,testfunc))
    // printf("Failed to invoke.\n");

    //const char *buf = "print('Hello World')";
    //luaL_dostring(L,buf);

    lua_close(L);
    return 0;
}

test.lua

function show()  
    print("helloworld") 
    print(add2(1.0,2.0)) 
    print(sub2(20.1,19))
    print(l_sin(1))
end  

show()  

Results:

Call C function in Lua (lua-5.2.3)

Quote blog post: http://www.cnblogs.com/stephen-liu74/archive/2012/07/23/2469902.html