lua-users home
lua-l archive

Re: string like arrays

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> there is some how, in Lua, to access string bytes like an array; 
> something like what we can use in C or Pascal?
> 
> examples:
> 
> s = 'Lua race'
> print( a[5] ) --> prints "r"
> 
> It would be very desirable to be able to write too, like:
> 
> s[5] = 'f'
> print( s ) --> prints "Lua face"
Not with Lua strings since they're immutable. But you can roll something like:
function mutstring (s)
 assert(type(s) == "string", "string expected")
 local ms = s or ""
 local u = newproxy(true)
 local mt = getmetatable(u)
 local relatpos = function(p)
 local l = #ms
 if p < 0 then p = l + p + 1 end
 if p < 1 then p = 1 end
 return p, l
 end
 mt.__index = function(_, k)
 assert(type(k) == "number", "number expected as key")
 local k, l = relatpos(k)
 if k <= l then
 return ms:sub(k, k)
 end
 end
 mt.__newindex = function(_, k, v)
 assert(type(k) == "number", "number expected as key")
 assert(type(v) == "string" and #v == 1, "character expected as value")
 local k, l = relatpos(k)
 if k <= l + 1 then
 ms = ms:sub(1, k - 1) .. v .. ms:sub(k + 1, l)
 end
 end
 mt.__len = function(_) return #ms end
 mt.__tostring = function(_) return ms end
 return u
end
Test:
> s = mutstring("Lua race")
> print(s[5])
r
> s[5] = "f"
> print(s)
Lua face
Cheers,
Luis.
-- 
A mathematician is a device for turning coffee into theorems.
 -- P. Erdos 
-- 
Luis Carvalho
Applied Math PhD Student
Brown University

AltStyle によって変換されたページ (->オリジナル) /