lua table 基本使用

本文介绍了一个使用Lua CAPI创建并操作Table的具体例子。通过C语言代码展示了如何构造一个包含不同类型元素的Table,并演示了如何从该Table中读取这些元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

table在Lua中唯一的数据结构,其它语言提供的各种数据结构Lua都是用table来实现的 。下面是一个C API操作table的例子。

#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main()
{
        
lua_State *L;
        L = luaL_newstate();
        luaL_openlibs(L);

        // ta = {'AA', 'BB', {'CC', 'DD'}}
        lua_newtable(L);
        //依次将各个元素放入table
        lua_pushnumber(L,1);
        lua_pushstring(L, "AA");
        lua_rawset(L,1);

        lua_pushnumber(L,2);
        lua_pushstring(L, "BB");
        lua_rawset(L,1);

        lua_pushnumber(L,3);
        lua_newtable(L);
        lua_pushstring(L, "CC");
        lua_rawseti(L,-2,1);

        lua_pushstring(L, "DD");
        lua_rawseti(L,-2,2);
        lua_rawset(L,1);

        lua_setglobal(L,"ta");
        //此时栈中为空,此处省略其他操作
        //将ta压入栈顶
        lua_getglobal(L, "ta");
        //获得第一个元素
        lua_rawgeti(L, 1,1);
        if(lua_type(L,-1) == LUA_TSTRING)
                printf("%s", lua_tostring(L,-1));
        lua_pop(L,1);

        lua_rawgeti(L, 1,2);
        if(lua_type(L,-1) == LUA_TSTRING)
                printf("%s", lua_tostring(L,-1));
        lua_pop(L,1);

        lua_rawgeti(L, 1,3);
        if(lua_type(L,-1) == LUA_TTABLE)
        {
                //因为第三个元素是table,所以继续获得它的第一个元素
                lua_rawgeti(L, -1,1);
                if(lua_type(L,-1) == LUA_TSTRING)
                        printf("%s", lua_tostring(L,-1));
                lua_pop(L,1);

                lua_rawgeti(L, -1,2);
                if(lua_type(L,-1) == LUA_TSTRING)
                        printf("%s", lua_tostring(L,-1));
                lua_pop(L,1);                
        }
        lua_pop(L,1); //此时栈顶为ta
                             
        lua_close(L);
}
<think>我们被要求提供Lua表的使用指南和基本操作。根据引用内容,特别是引用[1]和引用[3],我们知道Luatable库提供了一系列操作表的函数,如插入、删除、排序、连接等。同时,引用[4]告诉我们tableLua中的一种基本数据类型,可以用来表示数组、列表、记录等。 我们将按照以下结构组织回答: 1. 介绍Lua表(table)的基本概念和特性。 2. 讲解如何创建表。 3. 详细介绍table库的常用函数,如table.insert, table.remove, table.sort, table.concat等。 4. 提供一些示例代码。 5. 最后生成相关问题。 注意:在回答中,我们将使用行内数学表达式(如$O(n)$)和独立公式(如排序算法的时间复杂度)时,按照指令要求使用$...$和$$...$$格式。同时,在适当的地方添加引用标识。 下面开始回答:</think>### Lua 表(Table使用指南与基本操作 Lua 中的 **表(table)** 是核心数据结构,可表示数组、字典、对象等,具有极高灵活性。以下是详细指南: --- #### 一、表的基本特性 1. **动态创建** 无需预定义大小,自动扩容: ```lua local t = {} -- 创建空表 local arr = { "a", "b", "c" } -- 数组式表 local dict = { name = "Lua", version = 5.4 } -- 字典式表 ``` 2. **混合类型索引** 支持数字、字符串、甚至函数作为键: ```lua t[1] = 100 -- 数字索引 t["key"] = "value" -- 字符串索引 t.key2 = true -- 等价于 t["key2"] = true (语法糖) ``` 3. **元表(Metatable)** 通过元表实现面向对象和运算符重载(需单独讲解)。 --- #### 二、核心操作函数(table 库) | 函数 | 作用 | 示例 | |------|------|------| | `table.insert(t, [pos,] value)` | 插入元素 | `table.insert(t, 1, "x")` → 头部插入"x" | | `table.remove(t, [pos])` | 删除元素 | `table.remove(t, 2)` → 删除索引2的元素 | | `table.sort(t, [comp])` | 排序 | `table.sort(t)` → 默认升序排序 | | `table.concat(t, [sep])` | 连接为字符串 | `table.concat({"a","b"}, "-")` → "a-b" | | `table.move(a, f, e, t)` | 移动元素 | `table.move(a,1,3,2)` → 将元素1-3移动到位置2 | --- #### 三、常用操作示例 1. **遍历表** ```lua for k, v in pairs(t) do -- 遍历所有键值对 print(k, v) end for i, v in ipairs(t) do -- 仅遍历数字索引(连续数组部分) print(v) end ``` 2. **数组合并** ```lua local t1 = {1, 2} local t2 = {3, 4} for _, v in ipairs(t2) do table.insert(t1, v) end -- 结果:t1 = {1, 2, 3, 4} ``` 3. **自定义排序** ```lua local scores = {{name="Alice", score=90}, {name="Bob", score=85}} table.sort(scores, function(a, b) return a.score > b.score -- 按分数降序 end) ``` --- #### 四、性能注意事项 1. 避免在循环中频繁 `table.insert()`,推荐预分配大小(如 `local arr = {}; for i=1,1000 do arr[i]=0 end`)。 2. 大规模数据排序时,`table.sort()` 的时间复杂度为 $O(n \log n)$[^1]。 3. 稀疏数组(含 `nil` 空隙)会降低 `ipairs` 效率。 --- #### 五、应用场景 - 配置数据存储(如游戏道具表) - 动态数据结构(队列、栈) - 模块封装(通过表组织函数) - 面向对象实现(结合元表) > 引用说明:本文涉及的函数均来自 Lua 标准库 `table`[^1],数据类型定义参考 Lua 官方手册[^4]。 ```lua -- 示例:栈的实现 local stack = {} function stack.push(item) table.insert(stack, item) end function stack.pop() return table.remove(stack) end ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值