DivideByZero
DivideByZero

Reputation: 461

file.write not working from a different .lua

I wrote a lua function to add entered text to a users.txt in a specific manner, and that works fine when executed alone, but when i require it in main.lua it works- but never writes to users.txt. These are my two file's codes:

adminprograms.lua:

function adduser()
    print("Username")
    local username = io.read()
    print("Password")
    local password = io.read()
    print("State")
    local state = io.read()
    state = state.upper(state)
    print(state.."-"..username.."-"..password)
    --------------the code that dosent work
    local users = io.open("users.txt", "a" )
    users.write(users , state.."-"..username.."-"..password.."\n")
end

main.lua:

require "adminprograms"
loginstate = "admin"
repeat
local command = io.read()
if loginstate == "admin" and command == "newuser" then
    adduser()
end
until false

Why is this? They are both in the same folder along with users.txt. I am running Windows 64 bit if that matters at all. No errors are thrown.

Upvotes: 1

Views: 361

Answers (2)

Oliver
Oliver

Reputation: 29483

I can't see anything wrong but

  • This can't be code you ran since the last line would cause an error. Although not related to the error, it indicates there might be other code that you didn't put that could be source of error.
  • The write operations are buffered (they get written to disk only when the write buffer is full) so to be sure, you should close() the file object or at least flush() it:

    ... Call users:write() as (many times as) required, then when done:
    users:close()
    

    Or

    ... 
    users:write() -- if you're going to check the file contents in an editor:
    users:flush()
    

Stylistic (not related to problem): use the colon notation so you don't have to repeat the object: users:write() instead of users.write(users).

Upvotes: 2

Randy Hudson
Randy Hudson

Reputation: 494

adduser should work as expected if you put a users:close() call at the end.

The reference manual says "Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen." In the stand-alone case that happens right away, at program termination. (More precisely, the file handle is marked for finalization, the finalizer being to close the file, and finalizations are executed at the end of the Lua state.) But since main.lua doesn't immediately terminate, the garbage collection/finalization is postponed.

Upvotes: 3

Related Questions