How to take a word and then do a count of how many letters there are in a word and then read each letter individually

i need the computer to select a few words and make a random choice of one of the words
Then he will do a count of the letters and then I will be able to extract each letter individually

The idea of this should be as far as I understand:
Make a table in which to put the words, then select one of the words, then take to a new variable that will count the letters and then I can take those letters and put them each one separately
Such as: apple, cucumber, tomato
Take the word apple and separate the letters.
That I can do a word completion game and so on.
Such as: a_pl_

This game template (Five Letters) might help you.

1 Like

Thank you,
I went through the material and it is still not clear to me how it works
I would love if someone could add it for example from 2-3 words how to extract what commands

Thanks in advance

I’m not entirely sure what you are trying to achieve, but based on this and your other thread, I’ve made a very basic project that I think does what you want. Hope this helps.

local wordList = {"apple", "orange", "banana", "pear", "mango", "lemon", "kiwi", "plum"}
local wordOnScreen = display.newText({text = "", x = display.contentCenterX, y = display.contentCenterY})
local blankPositions
local currentBlank = 1

local function displayWordWithBlanks(word, blanks)
	wordOnScreen.text = word
	for i = 1, #blanks do
		local pos = blanks[i]
		wordOnScreen.text = wordOnScreen.text:sub(1, pos-1).."_"..wordOnScreen.text:sub(pos+1)

local function onKey(e)
	if e.phase == "down" then
		local key = e.keyName
		local blankPos = blankPositions[currentBlank]
		wordOnScreen.text = wordOnScreen.text:sub(1, blankPos-1)..key..wordOnScreen.text:sub(blankPos+1)
		currentBlank = currentBlank + 1
		if currentBlank > #blankPositions then
			-- all blanks filled

local randomWord = wordList[math.random(1, #wordList)]
blankPositions = {2, 4}
displayWordWithBlanks(randomWord, blankPositions)
Runtime:addEventListener("key", onKey)
1 Like



i would appreciate it if you could please explain how this works section by section

local composer = require( “composer” )
local scene = composer.newScene()

local widget = require( “widget” )

local loadsave = require(“loadsave”)
playerData = loadsave.loadTable(“playerData.json”)

– Revmob Integration
local revmob = require( “plugin.revmob” )
local revmobAppId = “5495a1d748e114ae1204d11f” – Replace this with your the app id
local placementID = “5532c8ed754d13e94a2c70d1” – Replace this with your placement id

– This will load and display a banner ad.
local function adListener( event )
if ( event.phase == “sessionStarted” ) then – Successful initialization
– Load a RevMob ad
revmob.load( “banner”, placementID )
elseif ( event.phase == “loaded” ) then – The ad was successfully loaded
– Show the ad placementID, { yAlign=“top” } )
revmob.init( adListener, { appId=revmobAppId } )

– Code outside of the scene event functions below will only be executed ONCE unless
– the scene is removed entirely (not recycled) via “composer.removeScene()”
local _S = {}
_S.W = display.contentWidth
_S.ACW = display.actualContentWidth
_S.ACH = display.actualContentHeight
_S.H = display.contentHeight
_S.T = display.screenOriginY – Top
_S.L = display.screenOriginX – Left
_S.R = display.viewableContentWidth - _S.L – Right
_S.B = display.viewableContentHeight - _S.T-- Bottom
_S.CX = math.floor(_S.W / 2) – Middle along x-axis
_S.CY = math.floor(_S.H / 2) – Middle along y-axis

– Game Specific Variables
local wordlist = require(“words”) – require in the file words.lua
local possibleWords = wordlist.possibleWords – assign the table to possibleWords

local answerLetters = {} – This holds the letters that go in the empty boxes
local playerLetters = {} – This holds the button widget the player uses to play the game

local txt_playerScore, txt_tutorial – Text object for player score and player tutorial
local currentScore = 0 – The current score of the game

local currentWord = “” – The current word
local currentWordTable = {} – This table will hold the shuffled word and is then used for the playerLetters table

local timerBar, tmr_moveTimerBar – declares the bar the player sees and the timer we use
local timerBarScale = 1 – The scale of the timer bar starts at 1, or 100%

local gameOverTitle, gameOverWord, btn_returnToMenu – game over forward declares

– Utility Functions
local function shuffleTable( t ) – For a better understanding, read
local rand = math.random
assert( t, “shuffleTable() expected a table, got nil” )
local iterations = #t
local j

for i = iterations, 2, -1 do
    j = rand(i)
    t[i], t[j] = t[j], t[i]


– Scene event functions
local function onBackTouch( event ) – Return the player to the menu
if ( “ended” == event.phase ) then
revmob.hide( placementId )

local function getWord() – Get a new word, update the score, reset the timer bar, and insert letters into the buttons for the player
currentWord = possibleWords[math.random(1,#possibleWords)]
print(currentWord) – Uncomment this line to see the correct word for the current level
txt_playerScore.text = currentScore
timerBarScale = 1

for i=1,string.len(currentWord) do -- split the word into an array
    currentWordTable[i] = currentWord:sub(i,i)

shuffleTable(currentWordTable) -- shuffle the table

for i=1,#playerLetters do
    playerLetters[i].value = currentWordTable[i]

if(currentScore > 1) then -- hide the tutorial
    txt_tutorial.alpha = 0


local function onLetterTouch(event) – When a player button is touched, insert the letter into one of the empty 5 boxes. If the button is already ‘active’, then reset the letter.
if ( “ended” == event.phase ) then
local id =

    if( == 1) then -- If the player hasn't touched the button, then add the letter to the row above.
        for i=1,#answerLetters do
            if(answerLetters[i].text == "") then
                answerLetters[i].text = string.upper(playerLetters[id].value)

       = 0.5
       = i


        local playersAnswer = "" -- gather the letters into a string for comparison later on
        for i=1,#answerLetters do
            playersAnswer = playersAnswer .. string.lower(answerLetters[i].text)
        if(playersAnswer == currentWord) then -- If the player has completed the word and it's correct, get a new word. Continue until time runs out.
            local function clearWord()
                for j=1,#answerLetters do
                    answerLetters[j].text = ""

                    playerLetters[j].value = ""
                    playerLetters[j].alpha = 1

            timer.performWithDelay(350, clearWord, 1)

            currentScore = currentScore + 1
        -- If the player HAS touched the letter, remove it from the row above and 'reset' the button. = 1
        answerLetters[].text = ""


local function moveTimerBar() – Reduce the timer bar to simulate a time limit within the game. Once timer bar hits 0, it’s game over.
timerBarScale = timerBarScale - 0.0025
timerBar.xScale = timerBarScale

if(timerBarScale <= 0) then -- on game over, stop the game and display the current word
    for i=1,#playerLetters do

    gameOverWord.text = "You could've got "..currentWord.."."
    gameOverTitle.alpha = 1
    gameOverWord.alpha = 1
    btn_returnToMenu.alpha = 1

    playerData["bestScore"] = currentScore
    loadsave.saveTable(playerData, "playerData.json")


– create(), Code here runs when the scene is first created but has not yet appeared on screen
function scene:create( event )

local sceneGroup = self.view

local background = display.newImageRect(sceneGroup, "images/game/gamebackground.png", 379, 569)
	background.x = _S.CX
	background.y = _S.CY

local lifebarBoxes = display.newImageRect(sceneGroup, "images/game/lifebar_boxes.png", 950, 237)
    lifebarBoxes.x = _S.CX
    lifebarBoxes.y = 275 + (_S.T * 0.5)

-- This for loop will go over answerLetters and playerLetters.
-- answerLetters: By default, this will be blank. As the player interacts with playerLetters, answerLetters will be filled out.
-- playerLetters: This creates the buttons the player interacts with. We store the id and assignment so we know which letter to add and which letter to remove.
for i=1,5 do
    answerLetters[i] = display.newText(sceneGroup, "", 0, 0, native.systemFontBold, 72)
        answerLetters[i].x = i * 155 - 65
        answerLetters[i].y = lifebarBoxes.y - 30

    playerLetters[i] = widget.newButton({
      width = 178,
      height = 158,
      defaultFile = "images/game/blank-box.png",
      overFile = "images/game/blank-box.png",
      font = native.systemFontBold,
      fontSize = 68,
      labelColor = { default={ 1, 1, 1 }, over={ 1, 1, 1, 0.5 } },
      onEvent = onLetterTouch
    playerLetters[i].id = i
    playerLetters[i].assignment = 0

-- Position the playerLetters. There are only 5 buttons, so manually positioning is okay here.
playerLetters[1].x, playerLetters[1].y = _S.CX      , _S.CY + 50 -- center square
playerLetters[2].x, playerLetters[2].y = _S.CX      , _S.CY - 115 -- top square
playerLetters[3].x, playerLetters[3].y = _S.CX + 185, _S.CY + 50 -- right square
playerLetters[4].x, playerLetters[4].y = _S.CX      , _S.CY + 215 -- bottom square
playerLetters[5].x, playerLetters[5].y = _S.CX - 185, _S.CY + 50 -- left square

-- Display a background for the players score
local img_playerScore = display.newImageRect(sceneGroup, "images/game/words_completed.png", 620, 142)
    img_playerScore.x = _S.CX
    img_playerScore.y = _S.B - 150

-- Keep track of the player score
txt_playerScore = display.newText(sceneGroup, currentScore, 0, 0, native.systemFont, 56)
    txt_playerScore.x, txt_playerScore.y = _S.CX+225, img_playerScore.y - 5

-- Display a quick how-to
txt_tutorial = display.newText(sceneGroup, "Create the word using the 5 letters above.", 0, 0, native.systemFont, 32)
    txt_tutorial.x, txt_tutorial.y = _S.CX, txt_playerScore.y + 105

-- Create the timer bar the will shrink over time
timerBar = display.newRoundedRect(sceneGroup, 0, 0, 718, 28.5, 9)
    timerBar.anchorX = 0
    timerBar.x = 42
    timerBar.y = lifebarBoxes.y + 86

-- gameOverTitle, gameOverWord, and btn_returnToMenu are displayed when the timer runs out.
gameOverTitle = display.newText(sceneGroup, "Time's Up!", 0, 0, native.systemFont, 64)
    gameOverTitle.x = _S.CX
    gameOverTitle.y = _S.CY - 50
    gameOverTitle.alpha = 0

gameOverWord = display.newText(sceneGroup, "You could've got "..currentWord..".", 0, 0, native.systemFont, 48)
    gameOverWord.x = _S.CX
    gameOverWord.y = gameOverTitle.y + 100
    gameOverWord.alpha = 0

btn_returnToMenu = widget.newButton({
  width = 345,
  height = 120,
  defaultFile = "images/game/mainmenu_btn.png",
  overFile = "images/game/mainmenu_pressed_btn.png",
  fontSize = 40,
  onEvent = onBackTouch
btn_returnToMenu.x = _S.CX
btn_returnToMenu.y = gameOverWord.y + 125
btn_returnToMenu.alpha = 0


– show()
function scene:show( event )

local sceneGroup = self.view
local phase = event.phase

if ( phase == "will" ) then
    -- Code here runs when the scene is still off screen (but is about to come on screen)

elseif ( phase == "did" ) then
    -- Code here runs when the scene is entirely on screen
    getWord() -- Get a random word from words.lua
    tmr_moveTimerBar = timer.performWithDelay(25, moveTimerBar, 0) -- Start the timer


– hide()
function scene:hide( event )

local sceneGroup = self.view
local phase = event.phase

if ( phase == "will" ) then
    -- Code here runs when the scene is on screen (but is about to go off screen)

elseif ( phase == "did" ) then
    -- Code here runs immediately after the scene goes entirely off screen



– destroy()
function scene:destroy( event )

local sceneGroup = self.view
-- Code here runs prior to the removal of scene's view


– Scene event function listeners

scene:addEventListener( “create”, scene )
scene:addEventListener( “show”, scene )
scene:addEventListener( “hide”, scene )
scene:addEventListener( “destroy”, scene )

return scene

want there to be buttons of all the letters that each button will receive a letter and when you click on the letter it will be written in one of the 5 blank boxes without text that are on the screen.
I need to have a random selection of a word from a vocabulary and then the word will be selected and then each letter will be in its box but will not be seen but it will be just by clicking a button and then when the word ends
Then there will be an end.

If you need the entire project to be explained maybe you should try the getting started guide before moving to a project like this. (not trying to be rude)

1 Like





If you need the entire project to be explained maybe you should try the getting started guide before moving to a project like this. (not trying to be rude)

First of all I’m new to all this,
Second thing I have already gone through the link you attached and here I turned for help after seeing that there I did not find a solution,
In all the examples there is a movement of objects, etc.,
There is no mention of the matter of the example handling of strings (words) and the separation of the strings of each letter / digit separately
Nor did I find this topic on the entire site.
It may be hiding somewhere but I still have not found after many searches.

This is a place of help,
I did not require anyone to do it, I just asked someone who has the desire to help the other.

I know, but my point is that you copy the entire file and require and explanation section by section when the only part of the code relevant for what you want to achieve are the functions (getWord and onLetterTouch). Anyways I get rid of some unnecessary part of the code and further comment on it. I hope now you can understand it better.
game.lua (10.5 KB)
words.lua (732 Bytes)


I believe what @premierghost was trying to say that you might benefit from brushing up on the basics.

The following are my personal opinions:

You asked for a section by section explanation for over 300 lines of code that you didn’t even format correctly, which makes reading said code very difficult. The code, however, isn’t all that difficult. It is dealing with the very basic concepts.

It is good to ask for help. In fact, it’s great and highly encouraged, but you should demonstrate at least a little effort from your side on “what you’ve done to accomplish what you want/need.” but you just asked someone else to “explain it for you.” without demonstrating that any self-initiative (again, you didn’t even bother to format the copied code).

When you can show others that you’ve tried to follow their advice and you still need help, then they will be much more likely to help you out. When you just list new requirements or specs without any of the aforementioned, it doesn’t inspire others to help.

Programming requires a lot of perseverance, practice and time. It’s better to start working from simple, perhaps even ground up projects, because projects that you can find online (like the one that has been linked) often contain lots of plugins and other junk that only serve to make the projects more difficult to understand.

Now, if you need help with string manipulation, you can find some tips and guides from Solar2D Docs - Lua String Manipulation.

1 Like

Thank you,
I thank you very much.
Good for you!