在 Lua 中添加字符串方法并修改自身

我该如何在string表中添加一个方法并在其中修改自身?

基本上,我正在尝试模仿Python中的io.StringIO.read方法,它在字符串中读取n个字符并返回它们,通过“消耗”来修改字符串。

我尝试过这个:

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

如何实现这一点?

原文链接 https://stackoverflow.com/questions/69258804

点赞
stackoverflow用户3574628
stackoverflow用户3574628

为了模拟 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 库中,因为该对象必须比仅为字符串更为复杂。

2021-09-20 21:38:13
stackoverflow用户11740758
stackoverflow用户11740758

你可以独立于字符串表格为数据类型字符串添加方法。

以下是短示例,展示了当字符串表格被删除后字符串方法仍然有效...

string=nil

return _VERSION:upper():sub(1,3)
-- 返回: 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
-- 输出:LUA
2021-09-21 10:50:40