Choosing a colour only once

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
davisdude
Party member
Posts: 1154
Joined: Sun Apr 28, 2013 3:29 am
Location: North Carolina

Re: Choosing a colour only once

Post by davisdude »

Another way to handle a one-time event would be with coroutines:

Code: Select all

local color = { 255, 255, 255, 255 }
local function randCol()
    color = { math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ) }
    coroutine.yield()
end
local randomColor = coroutine.create( randCol )

for i, v in ipairs( color ) do print( i, v ) end
print()
coroutine.resume( randomColor )
for i, v in ipairs( color ) do print( i, v ) end
You could even do better, though:

Code: Select all

local color = { 255, 255, 255, 255 }
local function randCol()
    local color = { math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ) }
    while true do
        coroutine.yield( color )
    end
end

local randomColor = setmetatable( 
    { coroutine.create( randCol ) }, 
    { 
        __call = function( tab, ... )
            return select( 2, coroutine.resume( tab[1], ... ) )
        end
    }
)

local function printColor() for _, v in ipairs( color ) do print( v ) end print() end
printColor()
color = randomColor()
printColor()
color = randomColor()
printColor()
GitHub | MLib - Math and shape intersections library | Walt - Animation library | Brady - Camera library with parallax scrolling | Vim-love-docs - Help files and syntax coloring for Vim
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 224 guests