[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: On the subject of Lua's grammar... --[[ ]]
- From: Philipp Janda <siffiejoe@...>
- Date: Fri, 28 Nov 2003 09:50:26 +0100
Leandro Candido schrieb:
Hello all,
As we are in suggestion time, i will make my one. Can you guys add range
operator? To use like:
for x in 0..10 do print(x) end or
for x in 'A'..'Z' do print(x) end
Of course the .. need be other letters/signs or we need to change the
concat operator, because it is "..".
Perhaps the best is the word "to":
for x in 0 to 10 do print(x) end, y = 0 to 10 or y = { 0 to 10 } --
equal y = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
What about this:
local function num_range_iterator( state, var1 )
-- state is the end of the iteration
var1 = var1 + 1
if var1 > state then
return nil
end
return var1
end
local function char_range_iterator( state, var1 )
-- state is the end of the iteration
local ret = num_range_iterator( state, string.byte( var1 ) )
return ret and string.char( ret )
end
function range( start, ending )
local stype, etype = type( start ), type( ending )
if stype == "string" and etype == "string" then
return char_range_iterator, string.byte( ending ),
string.char( string.byte( start )-1 )
elseif stype == "number" and etype == "number" then
return num_range_iterator, ending, start-1
else
error( "type error in function `range' (strings or numbers expected)" )
end
end
function from_to( start, ending )
local tab = {}
for x in range( start, ending ) do
table.insert( tab, x )
end
return unpack( tab )
end
--------- test -------------------------------------------------------
for x in range( 1, 10 ) do
print( x )
end
for x in range( 'A', 'Z' ) do
print( x )
end
local y = { from_to( 1, 10 ) }
for i,j in ipairs( y ) do
print( i, j )
end
Philipp