Lua calls C function

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.