小编Mos*_*lli的帖子

是否可以为字符串重载运算符?

是否可以将自己的运算符和元方法添加到Lua中的字符串中?

我希望做这样的事情:

local str = "test"

print(str[2]) --> "e"
print(str()) --> "TEST"
print(-str) --> "tset"
print(str + "er") --> "tester"
print(str * 2) --> "testtest"
Run Code Online (Sandbox Code Playgroud)

string lua operator-overloading operators

4
推荐指数
1
解决办法
157
查看次数

Lua函数在源代码中使用"self",但没有metamethod允许使用它们

我一直在挖掘Lua的源代码,包括他们网站的C源代码和Windows上的Lua的lua文件.我找到了一些奇怪的东西,我找不到任何关于他们为什么选择这样做的信息.

字符串库中有一些允许OOP调用的方法,方法是将方法附加到字符串,如下所示:

string.format(s, e1, e2, ...)
s:format(e1, e2, ...)
Run Code Online (Sandbox Code Playgroud)

所以我挖掘了模块表的源代码,发现像这样的函数table.remove()也允许同样的事情.

这是来自UnorderedArray.lua的源代码:

function add(self, value)
    self[#self + 1] = value
end

function remove(self, index)
    local size = #self
    if index == size then
        self[size] = nil
    elseif (index > 0) and (index < size) then
        self[index], self[size] = self[size], nil
    end
end
Run Code Online (Sandbox Code Playgroud)

这表明函数应该支持冒号方法.当我把桌子复制到我的新名单中时,看到了这些方法.这是一个使用table.insert作为方法的示例:

function copy(obj, seen) -- Recursive function to copy a table with tables
  if type(obj) ~= 'table' then return obj end
  if seen …
Run Code Online (Sandbox Code Playgroud)

oop lua list

3
推荐指数
1
解决办法
523
查看次数

标签 统计

lua ×2

list ×1

oop ×1

operator-overloading ×1

operators ×1

string ×1