Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua How to tell 1 from 1.0

I have a configuration script where the user can enter values either as an absolute value or a percentage value.

Absolute values are written as a value between 0.0 and 1.0 while percentage value are written as 0 to 100.

How can I distinguish 1 from 1.0? If I were to use strings, then it's not a problem for sure... I would like to keep this configuration simple and not have to rely strings.

Is this possible at all?

RECAP:

a = 1
b = 1.0

How to tell that a is not of the same type as b.

EDIT The configuration file look something like this:

local config = {}

-- A lot of comments describing how to configure

config.paramA = 1
config.paramB = 1.0

return config

In my processing script i read the configs like this:

config = require 'MyConfigFile'

config.paramA
config.paramB
like image 894
Max Kielland Avatar asked Dec 09 '22 01:12

Max Kielland


2 Answers

With Lua 5.3 came the integer data type which allows to differ between integer & floating point numbers and provides better performance in some cases. math.type is the function to get the subtype of a number.

local x = 1.0
print(math.type(x)) -- float
x = 1
print(math.type(x)) -- integer

If your percent value should be floating point too, William already called it: "a number is a number". You have to add an additional information to your number to differentiate, like packing it in a table with an identifier. Because you have just 2 cases, a boolean would be a cheap solution.

like image 161
Youka Avatar answered Jan 06 '23 04:01

Youka


From PIL you can see that a number is a number and therefore there's no way to distinguish 1 from 1.0 when working with them because they do have the same type

A way to to solve your problem is using a table that contains both the value and the type:

config.paramA = { 1, 'i' }
config.paramB = { 1.0, 'd' }

Or using a string and parsing it before converting to an integer:

config.paramA = '1'
config.paramB = '1.0'
like image 35
William Barbosa Avatar answered Jan 06 '23 03:01

William Barbosa