lua-users home
lua-l archive

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


(This has nothing to do with C bindings; all Lua.)

  Lua 5.0.3  Copyright (C) 1994-2006 Tecgraf, PUC-Rio
  > State = { GOOD=0, SIN=1 }
  > TrigOp = { COS=0, SIN=1 }
  > me = { state=State.SIN, op=TrigOp.SIN }
  > =me.state == State.SIN
  true
  > =me.state == TrigOp.SIN
  true

Yuck. Let's try again:

  > State={ GOOD={}, SIN={} }
  > TrigOp={ COS={}, SIN={} }
  > me = { state=State.SIN, op=TrigOp.SIN }
  > =me.state == State.SIN
  true
  > =me.state == TrigOp.SIN
  false

Yay! But...using a table just for a unique value seems easy to type, but
memory heavy. What about this:

  > local __enumID=0; function enum( names )
  >>   local t={}
  >>   for _,k in ipairs(names) do
  >>     t[k]=__enumID
  >>     __enumID = __enumID+1
  >>   end
  >>   return t
  >> end
  >
  > State = enum{ 'GOOD', 'SIN' }
  > TrigOp = enum{ 'COS', 'SIN' }
  > me = { state=State.SIN, op=TrigOp.SIN }
  > =me.state == State.SIN
  true
  > =me.state == TrigOp.SIN
  false

Since Lua strings are immutable and stored once, they're similar to
Ruby's Symbols. I suppose I could also simply do:

> me = { state='State.SIN', op='TrigOp.SIN' }
> =me.state == 'State.SIN'
true
> =me.state == 'TrigOp.SIN'
false


What do _you_ do when you need a simple, lightweight way to create some
unique values? Do you worry about cross-enumeration comparisons? Do you
use strings?