Skip to content

Instantly share code, notes, and snippets.

@stevedonovan
Created December 20, 2010 08:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevedonovan/748160 to your computer and use it in GitHub Desktop.
Save stevedonovan/748160 to your computer and use it in GitHub Desktop.
A Lua class for accessing individual characters in a string
--[[ Example:
sa = StringAccessor 'hello'
for c in sa:iter() do
print(c)
end
print(sa[1],sa[3])
print('end',sa[-1])
--]]
local char,byte = string.char, string.byte
local type,rawget = type,rawget
local function char_at(s,i)
return char(byte(s,i))
end
StringAccessor = {
__index = function(t,i)
local ti = type(i)
if ti == 'string' then return rawget(StringAccessor,i)
elseif ti == 'number' then
if i < 0 then i = #t.str + i + 1 end
if i <= #t.str then return char_at(t.str,i)
else error('out of range',2)
end
else
error("bad index type",2)
end
end;
__newindex = function(t) error("not modifiable!",2) end;
iter = function(t)
local i = 0
local s = t.str
return function()
i = i + 1
if i > #s then return nil end
return char_at(s,i)
end
end
}
--- Callable constructor
setmetatable(StringAccessor,{
__call = function(t,str)
return setmetatable({str=str},StringAccessor)
end
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment