# Using math.ceil

Hi there, I wanted to try using math.ceil for a game, but I have never used it before. The api info says that it returns the smallest number greater than or equal to X. Is there a way I can make it always be greater than? Because I can’t think of an instance where I would need to use it for equal to?

Not understanding what you’re asking for.

You want a function such that `ceil(5) == 6` and `ceil(5.1) == 6` instead of `ceil(5) == 5`?

Default behavior of `math.ceil` is that `math.ceil(x)` will be `x` if `x` is an integer, and will be `x - x % 1 + 1` if x`` has a fractional component. So: `ceil(5) == 5` and `ceil(5.1) == 6`

Yes, because I had a value for a table, and it was zero, and when I did math.ceil it returned 0, and I don’t want that.

I’m thinking of two scenarios you might be having.

The first is you actually want to do this:

``````index = math.ceil(x + 1)
``````

and the second is that you want to do this, given what you have said:

``````index = math.max(math.floor(x + 1), math.ceil(x))
``````

Both are different scenarios.

I think you want the first one because I am assuming that you have an array with indexes being integers `1` to `n` but `n` is defined from all numbers between `[0, n - 1]`.

Out of curiosity, why would you not want `math.ceil(0)` to return 0?

Lua has 1-indexed arrays, which would require incrementing the number by 1. I’m not sure what his issue is though, but I’ve had reasons where I would want behavior as in the first codeblock I described.

I believe that you can index at 0, just that iterators like `ipairs` and `pairs` skip over it.

Lua arrays start at 1, not 0. If you define a 0 key it becomes a mixed table because it is now a dictionary.

``````local a = {}

table.insert(a, "hello")

print(a[0]) -- nil
print(a[1]) -- hello

a[0] = "world"

print(a[0]) -- "world"
print(a[1]) -- hello
``````

What would be the point of the whole function then?

To ceil? `math.ceil` is equivalent to rounding upwards. If your parameter is already an integer, rounding up is equivalent to rounding to the current value.

2 Likes

Ooooooooooooh I see I thought it would do it even if it was an integer. Thanks