2. The language

Zacznij od początku
                                        

end

"len": the # operation.

function len_event (op)

if type(op) == "string" then

return strlen(op) -- primitive string length

elseif type(op) == "table" then

return #op -- primitive table length

else

local h = metatable(op).__len

if h then

-- call the handler with the operand

return (h(op))

else -- no handler available: default behavior

error(···)

end

end

end

See §2.5.5 for a description of the length of a table.

"eq": the == operation. The function getcomphandler defines how Lua chooses a metamethod for comparison operators. A metamethod only is selected when both objects being compared have the same type and the same metamethod for the selected operation.

function getcomphandler (op1, op2, event)

if type(op1) ~= type(op2) then return nil end

local mm1 = metatable(op1)[event]

local mm2 = metatable(op2)[event]

if mm1 == mm2 then return mm1 else return nil end

end

The "eq" event is defined as follows:

function eq_event (op1, op2)

if type(op1) ~= type(op2) then -- different types?

return false -- different objects

end

if op1 == op2 then -- primitive equal?

return true -- objects are equal

end

-- try metamethod

local h = getcomphandler(op1, op2, "__eq")

if h then

return (h(op1, op2))

else

return false

end

end

a ~= b is equivalent to not (a == b).

"lt": the < operation.

function lt_event (op1, op2)

if type(op1) == "number" and type(op2) == "number" then

return op1 < op2 -- numeric comparison

elseif type(op1) == "string" and type(op2) == "string" then

return op1 < op2 -- lexicographic comparison

else

local h = getcomphandler(op1, op2, "__lt")

Lua coding guideOpowieści tętniące życiem. Odkryj je teraz