Lua programming: mutual calls between Lua and C

Source: Internet
Author: User

Lua is a language with excellent scalability. Although its core is very simple, you can rely on the Lua library for most of the work. In addition, Lua can also expand program functions by calling each other with C functions. Embedding a Lua script in C allows you to modify the Lua code update program without re-compiling the code, and also provides you with a custom interface, this method follows the principle of separation of mechanisms and policies. Calling the C function in Lua can improve the program running efficiency. The mutual call between Lua and C is quite practical in the project. This article will explain the method of mutual call between Lua and C.

The primary issue for Lua and C to call each other is how to exchange data. Lua API uses an abstract stack to exchange data with C language, and provides the push element, the API operation stack for querying elements and pop-up elements. You can view the detailed documentation of each function in lua5.2. The elements in the stack can be accessed through indexes, from the bottom of the stack to the top of the stack is a positive integer that increases progressively from 1, and from the top to the bottom of the stack is a negative integer that decreases progressively from-1. The elements of the stack follow the FIFO rules.

I,CCallLua

First, let's take a simple example to learn how C calls Lua,

//test.luawidth = 10height = 20//test.c#include <stdio.h>#include <lua.h>#include <lualib.h>#include <lauxlib.h>int main() {  lua_State *L = luaL_newstate();  luaL_openlibs(L);  if(luaL_loadfile(L, "test.lua") || lua_pcall(L, 0,0,0)){    printf("error %s\n", lua_tostring(L,-1));    return -1;  }  lua_getglobal(L,"width");  lua_getglobal(L,"length");  printf("width = %d\n", lua_tointeger(L,-2));  printf("length = %d\n", lua_tointeger(L,-1));  lua_close(L);  return 0;}

Lual_newstate creates a new lua_state. All operations of C and Lua depend on this Lua environment. lual_openlibs loads the Lua standard library defined in lualib. H into lua_state.

Lual_loadfile loads and compiles Lua code from the file. After compilation, the program block is pushed into the stack,

Lua_pcall will pop up the program block and explain it in protection mode. In the code, call lua_pcall to define two global variables: width and length in lua_state.

Lua_getglobal pushes the value of global variables into the stack. width is first added to the stack, at-2, and length is at the top of the stack.

In addition to variables, C code can also directly call the functions defined in Lua.

//test.luafunction add(x, y)  return x+yend//test.c#include <stdio.h>#include <lua.h>#include <lualib.h>#include <lauxlib.h>#include <math.h>int main() {  lua_State *L = luaL_newstate();  luaL_openlibs(L);  if(luaL_loadfile(L, "test.lua") || lua_pcall(L, 0,0,0)){    printf("error %s\n", lua_tostring(L,-1));    return -1;  }  lua_getglobal(L,"add");  lua_pushnumber(L, 10);  lua_pushnumber(L, 20);  if(lua_pcall(L, 2, 1, 0) != 0){    printf("error %s\n", lua_tostring(L,-1));    return -1;  }  double z = lua_tonumber(L, -1);  printf("z = %f \n", z);  lua_pop(L, 1);  lua_close(L);  return 0;}

Lua_pcall (l, 2, 1, 0) indicates that two parameters are input, and a return value is expected. 0 indicates the index value of the error processing function in the stack, functions and parameters are displayed before the result is pushed in. Therefore, the Z index is-1.

II,LuaCallC

Lua can register the C function to Lua. The C function must follow a unified prototype defined in Lua. h,

Typedef int (*) (lua_state *)

When we use the C function to expand Lua, we usually compile all the C functions into an independent module to facilitate the addition of new functions.

//mylib.c#include <stdio.h>#include <lua.h>#include <lualib.h>#include <lauxlib.h>#include <math.h>static int myadd(lua_State *L){                int a = luaL_checknumber(L, 1);                int b = luaL_checknumber(L, 2);                lua_pushnumber(L, a+b);                return 1;}static const struct luaL_Reg mylib [] = {        {"add", myadd},         {NULL, NULL}};int luaopen_mylib(lua_State *L){  luaL_newlib(L, mylib);  return 1;}//call.lua#!/usr/local/bin/lualib=require "mylib"print(lib.add(1, 2))

Each C function called by Lua has its own private stack. The index of the push parameter increases progressively from 1, and the result value is directly pushed into the stack, when the function returns, all the pushed parameters are deleted, leaving only the result value. Mylib [] declares the list of all c Functions in the module. Each item maps the name of the C function in Lua. For example, in the code above, the myadd function is represented by add in Lua, the list must end with {null, null. Lual_newlib creates a table in the stack and registers the C function in the mylib array into this table. Luaopen_mylib loads the functions in this table into the Lua environment.

First, compile the C code into a dynamic link library,

Gcc-shared-FPIC-O mylib. So mylib. C-llua-lm-LDL

In the Lua code, require searches for mylib. So and calls the luaopen_mylib and luaopen _ Suffixes in the link library to be the same as the dynamic link library name. This is determined by the require search function method.

Lua programming: mutual calls between Lua and C

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.