Lua programming: Interaction Between lua and C, and lua Programming

Source: Internet
Author: User

Lua programming: Interaction Between lua and C, and lua Programming

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.


C/c ++ Programming

Thatax.blog.163.com/..28231/

It seems that generally C is used to call Lua.

Answer: lua calls the C language (for game scripts) and explains the role of the following code.

If LZ wants to learn LUA, He must read the book. Programming in Lua doesn't have to buy paper. At least he must have an electronic file. in the preface, he has already said that Lua is positioned as an extension language. therefore, there is no powerful library, and its advantage lies in its scalability and compatibility. Most of the functions must rely on external libraries. Only some very simple library functions can be called, but those powerful libraries can be used for learning. it takes some time to learn the basic databases.
As for the call of scripts and C, both of them can call each other, but after all, windows and C are more closely connected, therefore, generally C calls lua, but when the script needs to implement some functions that require c to write programs, it also calls c in lua.
Lua script is bound to C. The VC program written in c can be directly run in windows, lua cannot run directly without an interpreter. Generally, If You Want To directly use the lua program, you can use C to call it.

 

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.