Jump to content

[HELP] fileRead


Recommended Posts

Hi, how can i get the first line, then the second line of the file, when using fileRead?


 

local a = "EZ1"
local b = "EZ2"

local userJSON = fileCreate(":test/user.json")
if (userJSON) then

    fileWrite(userJSON, a.."\n"..b);

    fileClose(userJSON)
    print("Done")
end


addCommandHandler("b", function()
    local playerJSON = fileOpen("user.json")
    if playerJSON then
        playerJSONRead = fileRead(playerJSON, 500)
        fileClose(playerJSON)
        outputChatBox(playerJSONRead) --LINE 1
        outputChatBox(playerJSONRead) --LINE 2
    end
end)

 

Edited by TheMOG
Link to comment
59 minutes ago, TheMOG said:

fixed

Nice, I think it's a good habit to tell people how you were able to fix it, so in future other people can benefit from it. I don't know why you wanted to read it line by line, as you are dealing with a json file, you are meant to use:

fromJSON
toJSON

fileRead function simply returns a string, you have to use lua string functions to detect lines by checking for the new line escape sequences "\n". Here's a simple example that prints all the lines in a string:

local function getLineListFromString ( theString )
    local lineList = {}
    local lineStartIndex = 1
    for characterIndex = 1, string.len ( theString ) do 
        if ( string.sub ( theString, characterIndex, characterIndex ) == "\n" ) then 

            -- okay, we have a new line
            local lineEndIndex = characterIndex - 1
            table.insert ( lineList, string.sub ( theString, lineStartIndex, lineEndIndex ) )

            -- Now, we set the lineStartIndex after the new line escape sequence by 
            -- assigning characterIndex to lineStartIndex, and then incrementing it by 1
            -- for the next line
            lineStartIndex = characterIndex + 1
        end
    end
    return lineList
end

local ourText = [[This is line 1
This is line 2 
This is line 3
This is line 4
This is line 5
]]

local lineList = getLineListFromString ( ourText )

-- print all lines
for i, line in ipairs ( lineList ) do
    outputChatBox ( line )
end

Output:

This is line 1
This is line 2 
This is line 3
This is line 4
This is line 5

 

Edited by Saml1er
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...