Lua Math 101

1 + 1 = 2

by GraphicsSettings

Author Avatar

Why learn math in lua?

Lua can be used to make all sorts of powerful and creative events happen, but in order for us to accomplish that, we must use math! Like how you use math in real life, it can also be used in Lua. Whether it to define health after a few changes or to subtract or add to someones data.


A good example would be using math to make a formula of a sort and such. Here, I'll demonstrate how Lua can be used to determine XP amounts and requirements by level.

local Level = 1 -- player will start at level 1
local XP_Requirement = 25 -- required xp to level up
local XP_Current -- player's current xp amount

if XP_Current >= XP_Requirement then -- if player has reached xp requirement, run code below

 Level = Level + 1 -- level up the player
 XP_Requirement = XP_Requirement * Level * math.random(1, 5) -- create a new xp requirement using our own formula
 XP_Current = 0 -- reset our xp again

In the code above, I created a leveling up formula which will change the player's XP requirement everytime and make it unique!

So, math is useful?

Yes, it is useful. It can be used for other cases as well. Another case would be determining a chance of something happening, here's an example

local chance = math.random() -- randomly choose a number between 0-1

if chance < .3 then -- check if the chance is .3 or lower, then run the code below
 print('we were lucky lol') -- print to output to show the 'chance' was below .3


Those are the few ways math can be useful in Lua, hopefully you can find other ways to use numbers in Lua!

View in-game to comment, award, and more!