Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a way to divide numbers?

Asked by 5 years ago

Hey, so i've just made a random number generator, and i want to divide a number like (1984) into an x-cordinat and a z cordinat like x=19 and z=84. I've search all over the web for a fix, but i can't seem to find one. Can you help me?

0
you mean cutting the number in 2 (ABCD --> AB CD) if that's what your asking you should see string.sub, tonumber() and tostring() User#20388 0 — 5y
0
You can look up Modulus and Division (or do the above comment), dividing by 10 will take off the last digit and getting the modulus should give you the last digit. alphawolvess 1784 — 5y
0
It might be better to just use 2 math.random calls RubenKan 3615 — 5y

1 answer

Log in to vote
1
Answered by
BenSBk 781 Moderation Voter
5 years ago

To extract certain digits of a number, we need to use:

  • tostring to convert the number into a string
  • string.sub to extract certain characters from the string

First, we should convert the number to a string using tostring:

local coords = 1234
local str_coords = tostring(coords)

Now, we can use string.sub to get the first and last two characters from the string:

local x_coord = str_coords:sub(1, 2) -- The extraction is from the first to second character.
local y_coord = str_coords:sub(3, 4) -- The extraction is from the third to fourth character.

Notice our use of string:sub; all strings have the full string library built into them as methods, so this is an easier to use alternative to string.sub(str_coords, 1, 2) and string.sub(str_coords, 3, 4)

Ad

Answer this question