lua-users home
lua-l archive

Re: Numeric for loop with rationals

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


It was thus said that the Great Charles Heywood once stated:
> I am confused on why you think you can't:
> 
> Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio
> > function one() return 1 end
> > function two() return 2 end
> > function ten() return 10 end
> > for i=one(), ten(), two() do print(i) end
> 1
> 3
> 5
> 7
> 9
> >
 That only works for numbers. Soni would like a custom type, like
rationals, as in the first example:
	for x = r(1,10) , r(10,10) , r(1,10) do
	 print(x)
	end
 The stock numeric for in Lua is defined as:
 do
 local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
 if not (var and limit and step) then error() end
 var = var - step
 while true do
 var = var + step
 if (step >= 0 and var > limit) or (step < 0 and var < limit) then
 break
 end
 local v = var
 block
 end
 end
 The conversion of var, limit and step to numbers is preventing the use of
custom types that cannot be converted to numbers:
	for i = "1" , "10" , "2" do print(i) end
 -spc

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