Transferred from: http://www.cnblogs.com/ringofthec/archive/2010/10/22/lua.html
1. Build a new table
void Lua_createtable (lua_state *l, int narr, int nrec)
Create a new table and put it on top of the stack. Narr and Nrec Specify the number of pre-allocated elements for the table's array and hash sections, respectively
No return value
Stack height +1, stack top element is new table
#define LUA_NEWTABLE (L) lua_createtable (l, 0, 0) commonly used in this
2. Take the elements in the table
void Lua_getfield (lua_state *l, int index, const char *k)
Operation: arr = Stack[index] //arr must be a table
Stack.push (Arr[k])
Take the element with the key k in the table, where the table is a table on the stack pointed to by index
No return value
Stack height +1, stack top element is (Stack[index]) [K]
Note that this action will trigger the __index meta-method
3. Assigning values to elements in a table
void Lua_setfield (lua_state *l, int index, const char *k)
Action: arr = Stack[index]
Arr[k] = Stack.top ()
Stack.pop ()
Assigns a value to the element in the table with the key K (value is the top element of the stack), where the table is a table on the stack pointed to by index
No return value
Stack height-1, the popup is value
Note that this action will trigger the __newindex meta-method
4. Assigning Values to table elements and table elements
void Lua_gettable (lua_state *l, int index)
Operation: Ele = Stack[index]
Key = Stack.top ()
Stack.pop ()
Value = Ele[key]
Stack.push (value)
The corresponding table is assigned according to index; Take the top element of the stack as key, and pop the stack; Gets the value of the key in the table pressed into the top of the stack.
No return value
The stack height is constant, but a pop-up and press-in operation occurs, the key is popped, and the value is pressed in
Note that this action will trigger the __index meta-method
void Lua_settable (lua_state *l, int index)
Operation: ele = Stack[index]
Value = Stack.top ()
Stack.pop ()
Key = Stack.top ()
Stack.pop ()
Ele[key] = value
The corresponding table is assigned according to index; Take the top element of the stack to do value, pop it; Then take the top element of the current stack to do key, also pop up; Then assign the element of the table key to key as value
No return value
Stack height-2, first popup value, second popup key
Note that this action will trigger the __newindex meta-method
5. Some operations on table [does not cause the original method]
void Lua_rawget (lua_state *l, int index)
Same as the lua_gettable operation
But does not trigger the corresponding meta-method
void Lua_rawgeti (lua_state *l, int index, int n)
Operation: Ele = Stack[index]
Value = Ele[n]
Stack.push (value)
No return value
Stack +1, the new element at the top of the stack is value
does not trigger the corresponding meta-method
Same as the lua_settable operation
But does not trigger the corresponding original method
Operation: Ele = Stack[index]
Value = Stack.top ()
Stack.pop ()
Ele[n] = value
No return value
Stack-1, the top of the stack pops the value
does not trigger the corresponding meta-method
6. Copy the elements on the stack and press into the stack
void Lua_pushvalue (lua_state *l, int index)
Action: value = Stack[index]
Stack.push (value)
No return value
Stack +1
7. Create a meta-table
int lual_newmetatable (lua_state *l, const char *tname)
Operation: 1. Find Tname in the registry, if already registered, return 0, no to continue, and flat stack
Lua_getfield (L, Lua_registryindex, Tname)
if (!lua_isnil (L,-1))
return 0;
Lua_pop (L, 1);
2. Create a table and register and return 1
Lua_newtable (L)
Lua_pushvalue (L,-1)
Lua_setfield (L, Lua_registryindex, Tname)
Return 1
has a return value
Stack +1, the top element of the stack is a new table registered in the registry
8. Create a C value
void *lua_newuserdata (Lua_state *l, size_t size)
This function allocates a block of memory specified by size and placed on top of the stack
The return value is the address of the newly allocated block
Stack +1, top of Stack is UserData
The UserData is used to represent values in C in Lua. A complete userdata has its own meta-table, and the __gc method of the meta-table can be called when it is garbage collected
9. Register the C function into Lua, but there is no such thing, only c closures in Lua
void Lua_pushcclosure (lua_state *l, lua_cfunction fn, int n)
Press A C closure on the stack
When a C function is created, it is possible to bind several values above it to form a closure. These binding values can be accessed at any time when the C function is called.
Binding method: First press the N value to bind to the stack, then call Lua_pushcclosure (L, FN, n) to form a C closure
No return value
Stack – (N-1), pops up n elements (and those bound values), pressing into a cclosure
#define LUA_PUSHCFUNCTION (L, F) lua_pushcclosure (L, F, 0)
#define Lua_register (l, N, F) (Lua_pushcfunction (L, F), Lua_setglobal (l, N))
No return value
Stack does not change
This is a more common use of n as a key in Lua to press into a 0 bound value of the cclosure.
10. Call a LUA function
void Lua_call (lua_state* L, int nargs, int nresults)
Lua C API is characterized by "not a person in the fight" [I want to express the meaning is that Lua in a word, in the C API implementation is n sentence, there may be some doubts that why not directly with Lua, C API so troublesome, the answer is that some things can only use C API to achieve], so, call it Before, you need to layout the stack, first, to call the function to press the stack; Second, call to use the parameters are pressed into the stack; Then can call Lua_call, the call is over, to fetch the return value, it all to you pressure stack.
Operation:
Argn = Stack.pop ()
...//press into Nargs parameters altogether
Arg2 = Stack.pop ()
Arg3 = Stack.pop ()
Func = Stack.pop ()//function itself also pops up
Res1, Res2, ..., RESJ = func (arg1, arg2, ..., argn)
Stack.push (RES1)
Stack.push (Res2)
...//press in Nresults return value
Stack.push (RESJ)
No return value
After the call ends, the stack height increases nresults– (1 + nargs), if the Nresults parameter is set to Lua_multret, then Lua returns a few values, the stack is pressed into a few values, no forced to press into the Nresults value, insufficient is empty, redundant discarded
Note that This function is dangerous, and if an error occurs in it, it exits the program directly
The purpose of this function: not found, unless you can accept the error immediately exit, anyway, I am playing games, I can not afford, hehe, and incidentally, lauxlib.h in the lual_check* a family function is such, do not conform to the expected, direct exit, these functions should be careful, there is similar to the effect of assertions Fruit.
11. Protection downgrade with a LUA function
int Lua_pcall (lua_state* L, int nargs, int nresults, int errfunc)
parameters, behavior and Lua_call are the same, if no errors occur in the call, Lua_pcall = = Lua_call; But if an error occurs, Lua_pcall will catch it.
Errfunc points to an element on the stack, which should be a function, and when an error occurs
EF = Stack[errfunc]
Value = EF (errmsg)
Stack.push (value)
That is, at the wrong time, the error handler specified by Errfunc is called, and the return value of the handler is pressed onto the stack.
By default, you can give Errfunc a value of 0, and the actual effect is to specify such a function to make the error-handling functions Defaulterr (errmsg) return errmsg end.
This function has a return value Lua_errrun run-time error Lua_errmem memory allocation error [Note that this error will cause LUA not to invoke a fault handler] Lua_errerr An error occurred while writing the program and must check the return value:)
This function is strongly recommended, but in fact it is used by everyone:)
12. Protection downgrade with a C function
int Lua_cpcall (lua_state *l, lua_cfunction func, void *ud)
Call the C function in protected mode, Func can and only take a parameter from the stack, that is, UD, when there is an error, and Lua_pcall return the same error code, and leave the errmsg string at the top of the stack, if the call succeeds, it returns zero and does not modify the stack. All values returned from the Func are discarded.
Here are the questions to note:
1. "When there is an error", this error means a LUA error, not a C + + error. Using the Lua_call and lua_check* family functions in Func does not cause the program to quit, but it behaves like Lua_pcall.
2. When the call succeeds, the return value in Func is thrown away.
------------------------------------------------Gorgeous split-line--------------------------------------------------------- ---
1. What is the understanding of Lua's stack?
The LUA stack is similar to the following definition, which was created when the lua_state was created:
TValue Stack[max_stack_len]//The Stack_init function of lstate.c can be found in the knowledge
The data types of the stack include numeric values, strings, pointers, talbe, closures, etc., and here is an example of a stack:
Executing the following code allows you to render the picture on your LUA stack.
Lua_pushcclosure (L, func, 0)//create and press into a closure
Lua_createtable (L, 0, 0)//new and press into a table
Lua_pushnumber (L, 343)//press into a number
Lua_pushstring (L, "mystr")//press into a string
Here to illustrate, you press into the type has values, strings, tables and closures [In C appears to be different types of values], but the final is unified with TValue this data structure to save:), the following is a simple illustration of this data structure:
The TValue structure corresponds to all data types in Lua, is a {value, type} structure, which is the implementation of a dynamic type in Lua, which binds values and types together , uses TT to record the type of value, and value is a union structure, defined by value, You can see that this Union has four domains, which first explains the simple
P--A pointer can be stored, which is actually the light userdata structure in LUA
N--all values exist here, but int, or float
B--The Boolean value exists here, note that Lua_pushinteger is not present here, but exists in N, and b is stored in Boolean
GC--Other types such as table, thread, closure, and string require memory management garbage collection exist here
A GC is a pointer to a type defined by the Union Gcobject, as can be seen, with string, UserData, closure, table, proto, Upvalue, thread
The following figure can be drawn from the following conclusions:
1. Lua, number, Boolean, nil, light userdata four types of values are directly present on the stack element, regardless of garbage collection.
2. Lua, string, table, closure, UserData, thread exist only pointers in the elements of the stack, and they will be garbage collected after the end of the life cycle.
2. Conventions for LUA and C communication
Lua and C communication have such a convention: All LUA values are managed by LUA, the values produced in C + + do not know, similar to the meaning of the expression: " if you (c + +) Want what, you tell Me (LUA), I come to produce, and then put on the stack, You can only manipulate this value through the API, I am just in my world ", this is important because:
"If you want something, you tell me, I'll make it." It is guaranteed that LUA is responsible for the life cycle and garbage collection of variables in Lua, so the values must be created by Lua (the bookkeeping information used for life cycle management is added at the time of Creation )
"Then put on the stack, you can only manipulate the value through the API," the LUA API gives C a complete set of operating interfaces, which is equivalent to the agreed communication protocol , if LUA customers use this interface, then LUA itself will not have any "unexpected" error.
The phrase "I am my World" embodies Lua and C + + as a demarcation of two different systems, the value in C/s + +, which Lua does not know, and Lua is only responsible for its world.
3. The correspondence between LUA value and C value
|
C |
Lua |
| Nil |
No |
{value=0, tt = T_nil} |
| Boolean |
int not 0, 0 |
{value= non-0/0, tt = T_boolean} |
| Number |
Int/float et 1.5 |
{value=1.5, tt = T_number} |
| Lightuserdata |
void*, int*, various * point |
{value=point, tt = T_lightuserdata} |
| String |
Char str[] |
{VALUE=GCO, tt = t_string} gco=tstring obj |
| Table |
No |
{VALUE=GCO, tt = t_table} gco=table obj |
| UserData |
No |
{VALUE=GCO, tt = t_udata} gco=udata obj |
| Closure |
No |
{VALUE=GCO, tt = t_function} gco=closure obj |
As you can see, some of the types provided in Lua are corresponding to those in C, and also some types that are not available in C. Some of these medications are particularly illustrative:
Nil value, there is no correspondence in C, but a nil value can be pressed into Lua via Lua_pushnil
Note: The lua_push* family functions have the semantics of "create a type of value and press in" because all of the variables in Lua are created and saved in Lua, and for those LUA types that have a corresponding relationship with C, LUA passes an additional parameter from the API, The LUA variable that creates the corresponding type is placed on top of the stack, and LUA creates the corresponding variable at the top of the stack for no LUA type of the corresponding type in C.
For example: Lua_pushstring (L, "string") Lua creates a tstring obj based on "string", bound to the newly allocated top element of the stack
Lua_pushcclosure (l,func, 0) Lua creates a Closure obj based on Func, bound to the newly allocated top element of the stack
Lua_pushnumber (l,5) Lua modifies the top element of the newly allocated stack directly, assigning 5 to the corresponding domain
Lua_createtable (l,0, 0) Lua creates a Tabke obj, bound to the newly allocated top element of the stack
In summary, this is the flow of C value–> Lua value, whether you want to put a simple 5 into the world of Lua, or create a table that will cause
1. Stack top new allocation element 2. Bind or assign a value
Or to repeat a sentence, a C value into the stack is into the world of LUA, LUA will generate a corresponding structure and management, and henceforth no longer rely on this C value
Lua value–> C value, is implemented through the Lua_to* family API, it is simple to remove the corresponding C field value is OK, only those who have the corresponding value in C LUA value, such as table can not to C value, so API Bud No Provides an interface such as lua_totable.
Lua Common API