works:programmer:lua:index

This is an old revision of the document!


Язык программирования LUA

В чем разница между : и . в функциях lua

Разница лишь в том что что используя : функции не нужно передавать self как параметр. См. Пример

function MyClass:Func(a)
  self.name = a
end
 
function MyClass.Func2(self, a)
  self.name = a
end
 
object:Func("hello")
object.Func2(object, "hello")

Сделать простой дамп таблицы

function dump(var)
    local res = ""
    if type(var) == "string" then
        return '"' .. var .. '"'
    elseif type(var) == "number" then
        return "" .. var
    elseif type(var) == "function" then
        return '@'
    elseif type(var) == "boolean" then
        if var then
            return "true"
        else
            return "false"
        end
    elseif type(var) == "nil" then
        return nil
    elseif type(var) == "table" then
        -- ipairs   - indexed pairs
        -- pairs    - key named pairs
        res = "{"
        if not indexed then
            for k, v in pairs(var) do
                res = res .. dump(k) .. '=' .. dump(v) .. ','
            end
        end
        res = string.sub(res, 1, string.len(res)-1)
        res = res .. "}"
    else
        print(type(var))
    end
    return res
end
 
local socket = {my="test",table="example", "1", "2", "3"}
print(dump(socket))
works/programmer/lua/index.1581519955.txt.gz · Last modified: 2020/02/12 15:05 by Chugreev Eugene