C + + traversal LUA Table Sample _c language

Source: Internet
Author: User

C + + Gets the table data from the stack on the LUA stack.

Copy Code code as follows:

Map<string,string> traverse_table (lua_state *l, int index)
{
Map<string,string> data;
Lua_pushnil (L);
Now the stack: -1 => nil; Index => Table
index = index-1;
while (Lua_next (L, index))
{
Now stack: -1 => value; -2 => Key; Index => Table
Copying a key to the top of the stack and then doing lua_tostring on it will not change the original key value.
Lua_pushvalue (L,-2);
Now the stack: -1 => key; -2 => value; -3 => Key; Index => Table

Const char* key = Lua_tostring (L,-1);
Const char* value = lua_tostring (L,-2);

Data[key]=value;
Eject the value and copy key, leaving the original key as the next Lua_next parameter
Lua_pop (L, 2);
Now the stack: -1 => key; Index => Table
}
Now stack: Index => table (the last Lua_next returns 0 when it has already popped the last key left)
So the stack has been restored to its state when it enters this function.
return data;
}

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.