[Beginner Question] How to Get a Value by Place?

Hello, I am working on a simple GUI that will replace a number value with a particular image. So if I have the number “1002”, I need the script to be able to say, (Load 1.png, 0.png, 0.png, and 2.png). But that’s not all I want it to be able to do. So essentially my question is more to do with basic Lua and less with Garry’s Mod. How can I get any arbitrary number value and then have the script be able to detect what value is in the ten thousands, the thousands, the hundreds, the tens, and the ones place?


local function ExplodeNumber( num )
return string.Explode("", tostring( num ));

That is a function you can use to return a table containing each seperate number needed to be loaded.

Here is it in use and example use:

] lua_run_cl local t = ExplodeNumber( 1002 ) PrintTable( t )
1 = 1
2 = 0
3 = 0
4 = 2

Now, you need to load the corresponding textures, I would do it this way. Assuming the largest amount of numbers you can have is 4…

function ExplodeNumber( num )
return string.Explode("", tostring( num ));

local RunTextures = true;
local textures = {};

hook.Add(“HUDPaint”, “DrawTextures”, function()
if( RunTextures ) then
local t = ExplodeNumber( 1002 );

	for k, v in pairs( t ) do
		textures[ k ] = surface.GetTextureID("texture"..v..".vmt");

	RunTextures - false;

//now you have a table 'textures' containing all 4 texture ID's for use.


Something like that should work, just use textures[1] for the first number, texture[2] for the second, etc. texture[ int ] will return a texture ID for use with functions like surface.SetTexture.

local num = 1002 – that’s a number
local str = tostring(num) – you turn it into a string

local length = #str – this gives you the length of the string (so the number of digits in your number)

for i=1, length do
– loop through every digit in the number

-- string.sub(str, A, B) gives you a part of the string
-- starting at position A and ending with position B
-- so if A and B are the same values, you'll get a single character

local digit = string.sub(str, i, i)
-- do whatever you want with that digit
-- note that it's a string so you might want to turn it into
-- a number using tonumber() if you want to do comparisons or math with it

end – end of the loop

Ah well, looks like someone beat me to it. Hope that still helps.

thanks ninjas! you really came through in a pinch

/I salute u :dance: