悉野小楼

导航

lua中的table

Lua表格就是键值对, 可以嵌套

Luau类似json, json字符串的key要加引号, lua不能加, json数字key可以直接写, lua要加在数字外面加[], lua的key与值都可以是数字, 字符, 协程, 函数.

 

Lua表格赋值给另一个表格时, 其实是引用, 没有值复制

-- 创建一个表  
local originalTable = {key = "value"}  
  
-- 将原始表赋值给另一个变量  
local copiedTable = originalTable  
  
-- 修改复制的表  
copiedTable.key = "new value"  
  
-- 打印原始表的值  
print(originalTable.key) -- 输出: new value

如果想值复制表格, 这样修改复制表, 就不会影响原来的值

local originalTable = {key = "value"}  
local copiedTable = table.copy(originalTable)

 

Lua遍历有两种ipiars一般用作数组, 就是默认key不写, pairs遍历是键值遍历

local mytable =
{
    -- 字符做key, 不能加引号, 值要加引号(单引号, 双引号都可以)
    -- 数字做key, 要加[]
    -- lua每组键值对, 可以用,或;分隔
    hello = "hello",
    world = 'world';
    -- 没有指定key, 默认key为整数1
    {
        x = 100, y = 100
    },
    -- 没有指定key, key为整数2
    {
        x = 200, y = 200
    },
    [10] = 10,
    [15] = "num 15"
}

print("mytable length:", #mytable)
-- ipairs用来遍历连续的数组, 从1开始, 如果中间断了, 不会遍历到后面的
print("ipairs:")
for index, value in ipairs(mytable) do
    print("index:", tostring(index), ", value:", tostring(value))
end

print("pairs:")
-- pairs可以遍历所有的key, value
for key, value in pairs(mytable) do
    print("key:", tostring(key), ", value:", tostring(value))
end

输出结果:

mytable length:    2
ipairs:
index:    1    , value:    table: 0x21c36c0
index:    2    , value:    table: 0x21c3750
pairs:
key:    1    , value:    table: 0x21c36c0
key:    2    , value:    table: 0x21c3750
key:    world    , value:    world
key:    15    , value:    num 15
key:    10    , value:    10
key:    hello    , value:    hello

另一种遍历:

local pairCount = 2
local joinQueue = {1,2,3,4,5}
--i初始值为5, 每次减2, 如果i的值大于等于1时, 循环体可以执行
for i = #joinQueue, 1, -pairCount do
    local item1 = joinQueue[i]
    local item2 = joinQueue[i-1]
    print(item1, item2)
    
    table.remove(joinQueue, #joinQueue) --这儿修改表格不会影响i的值
    table.remove(joinQueue, #joinQueue)
end
--输出如下: 每次取尾巴两个值
--5       4
--3       2
--1       nil

 

学习测试时, 建议网上搜索"在线lua测试", 可以直接测试.

lua 调用函数只有一个参数时, 参数是字符串或表格, 可以不用括号,  表格的key为数字要加方括号, 可参见下面的表格打印

print('hello') 与  print 'hello' 相等, 参数为一个table时没测试

 

打印完整表格: 

local function print_table(t)
    local print_cache = {}
    local function sub_print(t, indent)
        if print_cache[tostring(t)] then
            print(indent .. "*" .. tostring(t))
        else
            print_cache[tostring(t)] = true
            if type(t) == "table" then
                for key, val in pairs(t) do
                     -- key可能是function 或 thread, 转成key_name字符串
                    local key_name = tostring(key)
                    local val_type = type(val)
                    if val_type == "table" then
                        print(indent .. "[" .. key_name .. "] => " .. "{")
                        sub_print(val, indent .. string.rep(" ", string.len(key_name) + 8))
                        print(indent .. string.rep(" ", string.len(key_name) + 6) .. "}")
                    elseif val_type == "string" then
                        print(indent .. "[" .. key_name .. '] => "' .. val .. '"')
                    else
                        print(indent .. "[" .. key_name .. "] => " .. tostring(val))
                    end
                end
            else
                print(indent .. tostring(t))
            end
        end
    end
    if type(t) == "table" then
        print("{")
        sub_print(t, " ")
        print("}")
    else
        sub_print(t, " ")
    end
end
local tbl = {
    [1] = 5, 
     [3] = 'test', 
     ['a'] = 77543, 
     [2] = { ['t'] = 9, ['moon'] = 1, [4] = {['thou'] = 1000, ['w'] = 10000, [143] = 'girl'}, ['what'] = 'why'},
     ['apple'] = 4
    }

local function test()
    print("hello")
end
-- 字符串"test"]为key, value为函数, 与tbl["test"] = test相同效果
tbl.test = test

-- 函数做为key, 值为字符串
tbl[test] = "my key is function"
local co = coroutine.create(function()
    print("hello coroutine")
end)
table.insert(tbl, co)
-- 协议作为key
tbl[co] = "my key is coroutine!"

print_table(tbl)

打印结果:

{
 [1] => 5
 [2] => {
          [moon] => 1
          [t] => 9
          [what] => "why"
          [4] => {
                   [thou] => 1000
                   [w] => 10000
                   [143] => "girl"
                 }
        }
 [3] => "test"
 [4] => thread: 0x24ea108
 [a] => 77543
 [apple] => 4
 [thread: 0x24ea108] => "my key is coroutine!"
 [function: 0x24ea050] => "my key is function"
 [test] => function: 0x24ea050
}

 

 

打印所有(表格, 单独类型, 都可以):

function print_all(...)
    for i, t in ipairs({...}) do
        if type(t) ~= 'table' then
            print(tostring(t))
        else
            print_table(t)
        end
    end
end

print_all({a = 5, b = "ccc"}, tbl, 4)

打印结果:

{
 [b] => "ccc"
 [a] => 5
}
{
 [thread: 000002350A5A6128] => "my key is coroutine!"
 [1] => 5
 [2] => {
          [what] => "why"
          [moon] => 1
          [t] => 9
          [4] => {
                   [thou] => 1000
                   [143] => "girl"
                   [w] => 10000
                 }
        }
 [3] => "test"
 [test] => function: 000002350BE82920
 [4] => thread: 000002350A5A6128
 [apple] => 4
 [a] => 77543
}
4

lua表增加元素, 可以如上面tbl.test = 值, 这儿test当成字符串了, 如果key为其它类型要加[], 如果数字, 协程, 函数,都要加[], 参照上面.

lua表删除元素, 如果是列表, 可以使用table.remove(listTab, pos), 返回删除的值; 如果不是列表, 使用piars遍历, 设置指定key的值为nil, 就可以了

function deleteKey(t, key)  
    for k, v in pairs(t) do  
        if k == key then  
            t[key] = nil  
            return true  
        end  
    end  
    return false  
end

 

table.concat 函数用于将一个数组(table)中的元素连接成一个字符串
local words = {"Hello", "world", "from", "Lua"}
local sentence = table.concat(words, " ")
print(sentence)  -- 输出 "Hello world from Lua"
 
table.move 函数用于将一个表(table)中的元素移动到另一个表或同一表的不同位置。它接受五个参数:源表、源表的起始索引、源表的结束索引、目标表的起始索引和目标表(可选,如果未提供,则默认为源表)。
local t = {1, 2, 3, 4, 5, 6, 7, 8, 9}
table.move(t, 2, 4, 6)
--t:{1, 5, 6, 7, 8, 9, 2, 3, 4}
for i, v in ipairs(t) do
    print(i, v)
end
--输出
1       1
2       2
3       3
4       4
5       5
6       2
7       3
8       4
9       9
 
table.pack 和 table.unpack 函数分别用于将一组值打包成一个表(table)和将一个表中的值解包成一组值。
local values = table.pack(1, 2, 3, 4, 5)
for i, v in ipairs(values) do
    print(i, v)
end
--[[输出
1       1
2       2
3       3
4       4
5       5
]]
local values = {1, 2, 3, 4, 5}
local a, b, c = table.unpack(values, 2, 4)
print(a, b, c)  -- 输出 "2 3 4"

 

posted on 2012-02-10 11:10  悉野  阅读(1076)  评论(0编辑  收藏  举报