Jump to content

Отобразить все элементы таблицы lua


Evgen

Recommended Posts

Приветствую!

Начал работать с таблицами в lua. Подскажите, как вывести все элементы таблицы. Таблица многомерная. Спасибо!

  • Like 1
Link to comment
Share on other sites

Существует множество способов для решения вашей задачи. Будем опираться на использование Lua внутри Vikingo Engine.

Способ через json:

local json = require"json"
local t = {a=100, b={c=200}}
print(json.encode(t))

1708426327-489604-lua-dump-table-json.jpg.3ef3c21fbcfadf5b6101a909a270ecbb.jpg

Способ через inspect:

local inspect = require"inspect"
local t = {a=100, b={c=200}}
print(inspect(t))

1708426434-866888-lua-dump-table-inspect.thumb.jpg.0a145486f6e438e31c0eba44f5970bac.jpg

Некоторые примеры из интернета на чистом Lua:

#1

function tprint(t, s)
    for k, v in pairs(t) do
        local kfmt = '["' .. tostring(k) .. '"]'
        if type(k) ~= "string" then
            kfmt = "[" .. k .. "]"
        end
        local vfmt = '"' .. tostring(v) .. '"'
        if type(v) == "table" then
            tprint(v, s or "" .. kfmt)
        else
            if type(v) ~= "string" then
                vfmt = tostring(v)
            end
            print(type(t)..(s or '')..kfmt..' = '..vfmt)
        end
    end
end

local t = {a = 100, b = {c = 200}}
print(tprint(t))

1708426785-676610-lua-dump-table-print1.thumb.jpg.da4a7de463c5d7a3801253b61dac7410.jpg

#2

function dump_table(o)
    if type(o) == "table" then
        local s = "{ "
        for k, v in pairs(o) do
            if type(k) ~= "number" then
                k = '"' .. k .. '"'
            end
            s = s .. "[" .. k .. "] = " .. dump_table(v) .. ","
        end
        return s .. "} "
    else
        return tostring(o)
    end
end

local t = {a = 100, b = {c = 200}}
print(dump_table(t))

1708426974-711408-lua-dump-table-2.thumb.jpg.06272851f821413c2c25ebd207d46801.jpg

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...