1

Currently I work on a project within the game Minecraft and OpenComputers. The main coding language is Lua.

Now, I need to find a nice solution to iterate through a string.

My current solution looks like this:

local config = "key1=type1\nkey2=type2\nkey3=type3"
local lines = {}
while true do
    local length = config:len()
    local s, f = config:find("\n")
    if s ~= nil then
        table.insert(lines, config:sub(1, s-1))
        config = config:sub(f+1, length)
    else
        table.insert(lines, config)
        break
    end
end

In this example I have a static string in the variable config but in the real code I read the lines from a config file.

My solution works, but I think it can be cleaner. Is there a cleaner solution?

6
  • If it works but you want to see if it could be cleaner, you should request a review on codereview.stackexchange.com Dec 8, 2017 at 17:04
  • I'm voting to close this question as off-topic because it belongs on codereview.stackexchange.com Dec 8, 2017 at 17:04
  • 2
    @StephenOstermiller in the future, please don't use Code Review as a reason to close a question. Evaluate the request and use a reason like too broad, primarily opinion-based, etc. Please see the section What you should not do in this answer to A guide to Code Review for Stack Overflow users Dec 8, 2017 at 17:19
  • Okay guys i'm sorry for my mistake on stackoverflow. Thank you for the information on "what i should not do" :) Dec 8, 2017 at 22:50
  • @ChristianNill Sam Onela's comment was actually directed at Stephen Ostermiller. Specifically, the part in that post where it says "Not all questions about analyzing code are off-topic on Stack Overflow, and not all code review requests are on-topic on Code Review". This was probably fine on both, quite frankly. I see a lot of people who conclude that just because something is on-topic on another site that it is automatically off-topic here, which is not the case.
    – Ajean
    Dec 9, 2017 at 1:57

1 Answer 1

2

If you want to iterate over the lines in a file, use io.lines:

local lines = {}
for l in io.lines("config.txt") do
    table.insert(lines, l)
end
1
  • The answer was soooo easy... Thank you very much. Sometimes i do not see the tree within a forest. Thank you Dec 8, 2017 at 14:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.