Search code examples
typesluaintegerdoublelua-5.2

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

Solution

  • 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.