Reference: Http://blog.163.com/[email protected]/blog/static/170499225201121504936823/
1. Edit C Program
Vim LUAC.C
#include <stdio.h> #include <lua.h> #include <lualib.h># Include <lauxlib.h>lualib_api int luaopen_mylib (lua_state *l);//Custom function static int my_add (lua_state *l) {int x = L Ua_tonumber (l,1); The first parameter, converted to a number int y = Lua_tonumber (l,2); The second argument, converted to a number int sum = x + y; Lua_pushnumber (L, sum); return 1; Returns the sum calculation result}static int showstr (lua_state *l) {//The first parameter passed in from LUA, const char *STR = lua_tostring (L, 1); printf ("c Program str =%s\n", str); return 0;} function list static struct Lual_reg funclist[] ={{"Add", My_add},//my_add () function, Lua is accessed using the name add {"Show", Showstr},//showst The R () function, which is accessed in Lua with the name show {null, NULL}///must finally have this};//register function list for easy extension//Our compiled dynamic library name is Mylib.solualib_api int Luaopen_mylib (Lua_ State *l) {lual_register (L, "Mylibfunc", funclist),//lua access Mylibfunc.add function with My_add return 1;} #if 0//directly registers a function Lualib_api int luaopen_mylib (lua_state *l) {lua_register (L, "add", My_add); return 1;} #endif
2. Editing LUA programs
Require "mylib" local sum = Mylibfunc.add (3,9) print ("sum=", sum) Local str = mylibfunc.show ("haha")
3. Compile C program for dynamic library
GCC Luac.c-shared-fpic-o mylib.so-i/usr/local/lj2/include/luajit-2.0/
4. Run test LUA call C program
The LUA T.lua output is as follows: sum= 12c program str = haha
Lua calls C function