lua-users home
lua-l archive

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


> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org]
> On Behalf Of meino.cramer@gmx.de
> Sent: vrijdag 20 juli 2012 5:39
> To: Lua mailing list
> Subject: value to string constant
> 
> Hi,
> 
> from the user input I get the wanted baudrate as an raw value
> - say
> 
>     115200.
> 
> I have to map this to a constant (in case of luars) which is
> 
>     "rs232.RS232_BAUD_115200"
> 
> which is a string despite the "." in the middle...
> 
> To prevent looping over all constants and forests of if-then-else stuff
> (there are more constants to map) I thought, that a table could do
> that...
> 
> But
> 
>     baudrate = { "115200", "rs232.RS232_BAUD_115200" }
> 
> and
> 
>     ui=115200
> 

The key you're trying to find is a number, while the table has a string as a
key. This is one of those little things that can easily go wrong. Do an
explicit coercion to prevent this.
Try;
     baudrate = { 115200, "rs232.RS232_BAUD_115200" }
     ui=115200

     local c = baudrate(tonumber(ui) or -1)
     print (c or "Baudrate not found")

tonumber(ui) returns nil if it can't convert which will throw an index
error, hence the 'or -1', so you'll only need to check whether 'c == nil'
(or another 'or' construct in the print statement)


> gives me another problem:
> 
>     baudrate.[ui]
>     baudrate.[tostring(ui)]
>     baudrate.ui
> 
> produces all 'nil' wiith lua -i
> 
> How can I map teh user input directly to the constant without iterating
> and/or 'if-ing' over dozens of possibilities?
> 
> Thank you very much in advance for your help and patience with a lua
> newbie... ! :)
> 
> Best regards,
> mcc
> 
> 
> 
>