Range Function


  • Implementation of pythons range() function with my own little extra features.

    Function:

    local range = function(x, y)
    	
    	local start = (y ~= nil and x-1 or 0)
    	
    	local max = (y ~= nil and y or x)
    	
    	return function(t)
    		
    		if t == nil then
    			
    			if start + 1 > max then return end
    			
    			start = start + 1
    			
    			return start
    		
    		else
    			
    			t = type(t[1]) == "table" and t[1] or t
    			local nt = {}
    			
    			local num = 1
    			for k, v in pairs(t) do
    				rawset(nt, num, {key = k, value = v})
    				num = num + 1
    			end
    			
    			return function() 
    				
    				local max = (x == nil and y == nil) and #nt or max
    				
    				if start + 1 > max  then return end 
    				
    				start = start + 1
    				
    				local key = nt[start].key
    				local value = nt[start].value
    				
    				return start, key, value 
    			end
    			
    		end
    		
    	end
    	
    end
    

    Examples:

    t = {["object"] = 5, [2] = "5", ["something"] = "cool"}
    
    for i in range(5)  do
    	print(i)
    end
    
    Output:
    1
    2
    3
    4
    5
    
    for i in range(2, 5) do
    	print(i)	
    end
    Output:
    2
    3
    4
    5
    
    for i, k, v in range(){ t } do
    	print(i, k, v)	
    end
    
    Output:
    1 2 5
    2 object 5
    3 something cool
    
    for i, k, v in range(2, 3){ ["object"] = 5, [2] = "5", ["something"] = "cool" } do
    	print(i, k, v)	
    end
    
    Output:
    2 object 5
    3 something cool
    

    Lemme know what you think in the comments!

  • Global Moderator

    @DragonSK16 Range's second argument is exclusive; range(5) should evaluate to [0, 1, 2, 3, 4]. Other than that not too bad


  • Your correct although, because it is lua. Table's tend to start [1,2,3,4,5]. So i originally was thinking of what you said, but i took lua into account, and kept theme.

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.