【问题标题】:Add method to string and modify self in Lua在 Lua 中添加方法到字符串并修改 self
【发布时间】:2021-11-14 10:05:08
【问题描述】:

如何向string 表添加方法并在其中修改 self ?

基本上,我试图模仿 python 中io.StringIO.read 方法的行为,它读取字符串中的n char 并返回它们,通过“使用”它来修改字符串。

我试过这个:

function string.read(str, n)
  to_return = str:sub(1, n)
  str = str:sub(n + 1)
  return to_return
end

local foo = "heyfoobarhello"
print(string.read(foo, 3))
print(foo)

输出是:

hey
heyfoobarhello

我预计第二行只有foobarhello

我怎样才能做到这一点?

【问题讨论】:

  • Lua 中的字符串是不可变的。您可以将字符串包装为跟踪从何处开始的对象。或者您可以更改 API 以返回字符串和子字符串。
  • @lhf 我明白了,谢谢。

标签: string lua io luajit


【解决方案1】:

要模仿 Python 的 io.StringIO 类,您必须创建一个对象来存储底层字符串和该字符串中的当前位置。从 IO 流中读取通常不会修改底层数据。

local StringIO_mt = {
  read = function(self, n)
    n = n or #self.buffer - self.position + 1
    local result = self.buffer:sub(self.position, self.position + n - 1)
    self.position = self.position + n
    return result
  end,
}
StringIO_mt.__index = StringIO_mt

local function StringIO(buffer)
  local o = {buffer = buffer, position = 1}
  setmetatable(o, StringIO_mt)
  return o
end

local foo = StringIO"heyfoobarhello"
print(foo:read(3))
print(foo:read())

输出:

hey
foobarhello

我不建议将此类或方法添加到 Lua 的 string 库中,因为对象必须比字符串更复杂。

【讨论】:

  • 你为什么只写 5.4 的代码?这个问题有LuaJIT标签,意思是Lua 5.1。
  • @EgorSkriptunoff 是的,我自己想通了,我刚刚删除了标签<something>。不用担心;)
  • @EgorSkriptunoff:我完全错过了那个标签。固定。
【解决方案2】:

您可以独立于字符串表向数据类型字符串添加方法。
一个简短的例子表明,如果字符串表被删除,字符串方法甚至可以工作......

string=nil

return _VERSION:upper():sub(1,3)
-- Returning: LUA

所以你可以添加一个方法...

-- read.lua
local read = function(self, n1, n2)
return  self:sub(n1, n2)
end

getmetatable(_VERSION).__index.read=read

return read

...对于所有字符串。
(不仅是_VERSION)

然后使用它...

do require('read') print(_VERSION:read(1,3):upper()) end
-- Print out: LUA

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2011-07-12
    • 2012-01-13
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2022-01-15
    相关资源
    最近更新 更多