我怎樣才能在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
結束
local foo = "heyfoobarhello"
print(string.read(foo, 3)
print(foo)
輸出是:
hey
嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿
我希望第二行只有foobarhello。
我怎樣才能做到這一點呢?
uj5u.com熱心網友回復:
為了模仿Python的io.StringIO類,你必須做一個物件來存盤底層字串和該字串中的當前位置。從一個 IO 流中讀取資料通常不會修改底層資料。
local StringIO_mt <const> = {
read = function(self, n)
n = n or #self.buffer - self.position 1
local result <const> = 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 <const> = {buffer = buffer, position = 1}。
setmetatable(o, StringIO_mt)
return o
end[/span]。
local foo = StringIO"heyfoobarhello"。
print(foo:read(3))。
print(foo:read()
輸出:
hey
foobarhello
我不建議將這個類或方法添加到Lua的string庫中,因為物件必須比字串更復雜。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324433.html
標籤:
