Print certain text based on string pattern

Using this test script to print some text:

X = 10
while true do
X = X - 1
	local function Text()
		if X == 1 then
			return "test"
		else
			return "tests"
		end
	end
	print(Text)
end

Looking to optimize the script. Looked into string patterns but not sure how to get the same results. Would like to know optimization is truly needed or not

You can use a for loop, for example:

for count = 1, 10, 1  do
	if count == 5 then
       print("Half")
    end
end

image

So there are some problems with this code.

X = 10
while true do
X = X - 1
	local function Text()
		if X == 1 then
			return "test"
		else
			return "tests"
		end
	end
	print(Text)
end
  • The variable Text is a function. You’re printing a function when you call print(Text). I assume this isn’t what you want. Instead try print(Text()). The pair of () call the function, so it can return the value you want.
Code
X = 10
while true do
X = X - 1
	local function Text()
		if X == 1 then
			return "test"
		else
			return "tests"
		end
	end
	print(Text())
end
  • I would look into parameters. You could instead do something like the code below (which is faster and more readable). This creates a function only once, instead of creating a function each time it’s needed:
Code
local function Text(X)
	if X == 1 then
		return "test"
	else
		return "tests"
	end
end
X = 10
while true do
	X = X - 1
	
	print(Text(X))--note the pair of () after Text, this calls the function
end
  • Another thing to note is that this loop probably doesn’t work. This is because lines of code without yields (things like wait() or other calls that stop code). To fix this, you can add ‘wait()’ after ‘print(Text)’ at the end of the loop.
Code
local function Text(X)
	if X == 1 then
		return "test"
	else
		return "tests"
	end
end
X = 10
while true do
	X = X - 1
	
	print(Text(X))
	wait() -- this yields the while loop. It can be a little confusing to explain exactly why this needs to be here, but just imagine that it's running too much too fast. 
end
  • I’d recommend considering what you want your function to accomplish. This code segment prints tests infinitely (besides printing test once). You might want to do something more like the code below ( where it prints tests 9 times then prints test). This is the while loop version of a for loop like another user suggested:
Code
X = 10
while X > 0 do
	X = X - 1
	if X == 1 then
		print("test")
	else
		print("tests")
	end
end
  • Something that I’d highly recommend is using the cmd bar to test simple code in studio without needing to play test each time. You could copy and paste code like the code above into the cmd bar, press enter, then see the results in the output window (go to the View tab to open these windows). This helped me a ton when I was learning Lua.