Daily Lua (6)-interaction and learning summary between Lua and C

Source: Internet
Author: User

As a compact scripting language, Lua is easy to embed into C/C ++ and is widely used in game AI. In fact, Lua can be used in any ever-changing logic, the underlying interface service implemented with C/C ++ can greatly reduce system maintenance costs.

Data Interaction Between Lua and C/C ++ is performed through the "stack". When operating data, copy the data to the "stack" and then obtain the data, each data in the stack is located through the index value. When the index value is positive, it indicates the offset index relative to the bottom of the stack. If the index value is negative, it indicates the offset index relative to the top of the stack, the index value starts with 1 or-1. Therefore, the index value at the top of the stack is always-1, and the index value at the bottom of the stack is always 1. The "stack" is equivalent to the geographic location of data between Lua and C/C ++. Each type of data has an access interface.

C. Call the method in Lua.

Lua stores the functions to be called.

function add(x,y)print("sum:"..x+y)return x+yend

C language calls

#include <lua.hpp>#include <stdio.h>int main(){int a=10,b=20;int result=0;lua_State *L = luaL_newstate();luaopen_base(L);luaL_dofile(L,"scene.lua");lua_getglobal(L,"add");lua_pushinteger(L,a);lua_pushinteger(L,b);lua_pcall(L,2,1,0);result=(int)lua_tonumber(L,-1);        lua_close( L);printf("result:%d\n",result);}

Running result:

One line.

1. header file containing Lua;

2. Add standard input and output;

5, 6. initialize two variables;

7. Create a Lua runtime environment;

8. Load the basic library;

9. Load the Lua script;

10. obtain global variables;

11, 12. input parameters to the stack;

13. Call the function without processing the result;

14. result output stack;

15. Disable Lua;

16. Print the result.

Obtain data in Lua in C

The Lua file is used to store configuration files.

app_name="testApp"id=1host_info={hostname="SuperMan",ip="128.0.0.1",}data={date="2013.2",user="Jack"}host_info.content=dataprint("Load .lua successful!")

The configuration file contains strings, numbers, and a nested table.

The following uses C for parsing:

#include <lua.hpp>#include <stdio.h>int table_next(lua_State *L, int i,char **k, char **v){if ( lua_next(L, i) !=0 ){*k = (char *)lua_tostring(L, -2);*v = (char *)lua_tostring(L, -1);lua_pop(L, 1);return 1;}elsereturn 0;}int main(){int id=0;int ret = 0 ;char *k=NULL;char *v=NULL;lua_State *L = luaL_newstate();luaopen_base(L);luaL_dofile(L,"s.lua");lua_pcall(L,0,0,0);lua_getglobal(L,"app_name");printf("application name is %s.\n",lua_tostring(L,-1));lua_pop(L,1);lua_getglobal(L,"host_info");lua_getfield(L,-1,"hostname");lua_getfield(L,-2,"ip");printf("Host name is %s,ip is %s.\n",lua_tostring(L,-2),lua_tostring(L,-1));lua_pop(L,2);lua_pushnil(L);printf("isTable:%d\n",lua_istable(L,-2));while(lua_next(L,-2)){printf("Get key %s\n",lua_tostring(L,-2));if(lua_istable(L,-1)){printf("Is table!\n");lua_getfield(L,-1,"date");lua_getfield(L,-2,"user");printf("\tuser:%s\n",lua_tostring(L,-1));printf("\tdate:%s\n",lua_tostring(L,-2));lua_pop(L,2);}else{printf("value is:%s\n",lua_tostring(L,-1)); }lua_pop(L,1);}lua_close(L);}

The stack model in interaction must be understood here.

Several important functions:

Lua_pushnil (lua_state * LUA );

Pushnil is the NIL that loads Lua into the stack. Nil is a type value in Lua. In C, you can regard it as null, in addition, a value such as lua_tostring is not obtained from the stack, that is, nil in Lua. The result is null.

Lua_next (lua_state * Lua, int index)

The lua_next (lua_state * Lua, int index) function is the main character in this example. It can traverse the table at the index in the specified interactive stack and retrieve (-1) each time) as a predecessor, a key at the position is about to obtain the key of the previous pair of elements of a pair of elements, then return this pair of elements of the table, and press the key to the stack first, press the value corresponding to the key into the stack. The result is that the key is placed at the (-2) position and the value is placed at the (-1) position. After a table is pushed to it, the (-3) position in this example. If the key is nil, the first pair of data by default will be randomly pushed into a pair of values. After All values are traversed, next returns 0.

Lua_pop (lua_state * Lua, int num)

As described above, this function pops up num values from the interaction stack of the Interaction handle. Here I have to explain another benefit of Lua as a configuration file-Lua handles the stack by itself, making the configuration file program safer. All the content pushed into the stack, as long as the function is called, Lua handles its memory by itself, without the intervention of programmers. Of course, this also shows that the memory in the stack cannot be taken away, that is, you cannot use the memory that pops up in the stack, such as the string memory, for other purposes. Otherwise, the memory may become invalid after pop.

Lua_getfield (Lua,-1, "name"); this API is mainly used to process tables. The first parameter is the interactive handle, the second parameter is the position of the table in the interactive stack, and the third parameter is the key in the preceding table. The result of this function is to extract the key value from the table and press it into the interactive stack. In this way, the table at the original location (-1) is compressed to a location (-2 ).

For the reading of nested tables, the table host_info is first read in the Code, which is currently in the-1 position of the stack. After pushnil, the table is changed to the-2 position. After next is called, press into a pair of key-value, which can be in the position of-2, the value is in-1, the previous sequential shift.

After knowing the location, you can get the value through the corresponding get.

Lua calls the C library

First, use C to write the function to be registered.

# Include <Lua. HPP> # include <math. h> # include <stdio. h> typedef int (* lua_cfunction) (lua_state * l); static int l_sin (lua_state * l) {double D = lual_checknumber (L, 1); lua_pushnumber (L, sin (d); return 1;/* Number of Results */} static const struct lual_reg mylib [] = {"lsin", l_sin}, {null, null}/* must end with null */}; extern int luaopen_mylib (lua_state * l) {// lua_register (L, "mylib", mylib); // lual_openlib (L, "mylib", mylib, 0); lual_register (L, "mylib", mylib); return 1 ;}

Theoretically compiled into the. So file can be called in Lua, but the following error is reported during compilation:

test3.c: In function ‘int luaopen_mytestlib(lua_State*)’:test3.c:44:6: error: cannot convert ‘luaL_Reg*’ to ‘lua_CFunction {aka int (*)(lua_State*)}’ for argument ‘2’ to ‘void lua_pushcclosure(lua_State*, lua_CFunction, int)’

Not solved yet ....

Lua learning stage summary

The motivation for learning Lua is just one sentence-qualified programmers should learn at least one language each year!

I am not very familiar with it. Most of the time I have learned some code by referring to examples on the Internet. I have not studied some of the points that require time to understand, but at least I have mastered a script language, it will soon be used.

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.