Receive input from user.

Hello. So I’m planning on making a text-based adventure game where it takes input (similarly to io.read();), and uses them as specific commands in the app. So at the bottom, I’d have a text-box that gets the input from such user, and then uses that as a command.

Thing is, I do not know how to go about this in S2D.

Solar2D Documentation — API Reference | Libraries | native | newTextBox (coronalabs.com)

Hi,

I am sure there are many approaches to this, but I have been working on something similar, though not through a text box, but text lines with actionable items.

This is only my process. You will need to build the proper structure.

  • Decide what your actionable key words are (move, look, etc…).

  • Take in a line of text (from the text box in your case) and use a pattern to match the starting word, which should be your actionable word. You could also try string.find but it’s limited.

  • Take action (call a function to parse) based on the result.

The process itself isn’t very difficult. But the patten work can be depending on the complexity of the input. Even though I am talking about one actionable keyword, you can pull complex data from a string to fine tune the function response even more if needed.

For instance, if your input is something like go left you could parse out both those values and then push to a function like <variable_with_function_name>(<variable_with_direction_string>).

Here is some working example code. It might help others jump start the proccess as well.

--##############################################################################
-- Actionable Line Parser
--##############################################################################

-- Action functions
local actions = {}

-- A `go` function
actions.go = function(parameter)
  print("Go "..parameter)
end

-- The input
local line_input = "go left"

-- A pattern
local pattern = "^%s*(%w+)%s+(%w+)%s*$"

-- Parse line
local action, parameter = string.match(line_input, pattern)

-- Call the function
actions[action](parameter)

I’m sure there are other ways, but this is what works for me. And my strings are much more complex.

Anyway, hope this helps. Patterns take a bit to learn, but even a basic knowledge (like myself) is extremely worthwhile. It has helped me solve a lot of problems.

-dev

1 Like

I’m glad to see (both here and on Discord) that I’m not alone in my love for CYOA / Text++ adventure/story games.

I’m also happy to see that we’re all playing with different approaches to creating/expressing the experience.

1 Like