originalfoo / Style

A nicer way to define LuaGuiElement prototypes
MIT License
2 stars 0 forks source link

ponder `color.gradient` #21

Open originalfoo opened 8 years ago

originalfoo commented 8 years ago

For use with smooth progress bar gradients.

Rough idea: Use metamethods such as __lt and __le to facilitate clean looking syntax

gradient = color.gradient '#F00' < 0.5 '#FF0' < 1 '#0F0`
originalfoo commented 8 years ago

Example of props once converted to raw proto format:

smooth_color = <color>, -- is this for 1 or 0?
other_smooth_colors = {
  { color = <color>, less_then = <num> },
  { color = <color>, less_then = <num> },
  -- ...
},
originalfoo commented 8 years ago

This won't work because equality operators always typecast result to boolean:

gradient = color.gradient '#F00' < 0.5 '#FF0' < 1 '#0F0`
originalfoo commented 8 years ago

It can be done with __add or __sub, for example:

function add(self, val)
  if type(val) == 'number' then
    self.t[#self.t].less_then = val
  else
    self.t[#self.t+1] = { color = val }
  end
  return self
end

gradient = setmetatable( { t = {} }, {
  __call = function( self, ... )
    self.t = {}
    return add( self, ... )
  end,
  __add = add,
  __sub = add,
} )

result = gradient 'foo' -0.5- 'bar' -1- 'baz'

for i,t in ipairs( result.t ) do
  print( tostring(i)..': '..t.color..' < '..tostring(t.less_then) )
end

Gives output:

1: foo < 0.5
2: bar < 1
3: baz < nil
originalfoo commented 8 years ago

On hold until Factorio 0.15 due to this