lua でよく見かける function tab:func() の動きについて個人的にメモ


:func の動きがおまじないぐらいでしか分かってなかったけど,なんとなく分かったのでメモ

my_table.function()my_table:function() の呼び方二通りがある

my_table.func()

local my_table = {}

function my_table.func()
    print('funk')
end

my_table.func() -- funk

my_table:func()

local my_table = {}

function my_table:func()
    print('funk')
end

my_table.func() -- funk

これらの違いは第一引数に self を取るかどうか

上のを書き換えると

function my_table:func(arg1, arg2) -> function my_table.func(self, arg1, arg2)

になる

文字列 string に対して一部を切り出すには sub メソッドを使うが,これは以下のように書き換えられる

local s = 'string'
print(s:sub(3)) -- ring

そのまま呼ぶのは宣言されていないからか出来ないっぽい

print('string':sub(3)) -- ')' expected near ':'

self に何が入るか

最上位のテーブルに項目名で値が代入される

local my_table = {
    pink =  'Yup',
    green = 'Yup',
    white = 'Yup'
}

function my_table:check(s)
    if self[s] then
        print(self[s])
    else
        print('hmm')
    end
end

my_table:check('pink') -- Yup
my_table:check('green') -- Yup
my_table:check('white') -- Yup
my_table:check('yellow') -- hmm

この使い方ができるのでクラス的な書き方ができる

local person = {}

function person:init(first, last)
    self.first = first
    self.last = last

    return self
end

function person:say()
    local fmt = "I'm %s %s"
    print(fmt:format(self.first, self.last))
end

local p = person:init('John', 'Henry')
p:say() -- I'm John Henry
--[[
    {
        last = "Henry",
        init = "function: 0x7fe8115000f0",
        say = "function: 0x7fe811500120",
        first = "John"
    }
]]