【问题标题】:Writing to a file from a TextBox Lua从 TextBox Lua 写入文件
【发布时间】:2016-01-15 08:00:23
【问题描述】:

最近我一直在尝试添加一个基本单词。我想做它,所以您点击文本字段,然后输入您需要的内容,然后将其写入 .txt 文件(是否预先创建) 我不擅长编码,我正在努力使用示例/其他人 Stack Exchange问题学习了。我所拥有的只是一些不能一起工作的代码,我不确定我需要做什么才能让它们工作(代码不是我的)

local textBox = native.newTextBox( 200, 200, 280, 140 )
textBox.text = "This is line 1.\nAnd this is line2"
textBox.isEditable = true


local file = io.open( filePath, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )

print( "Contents of " .. filePath )
print( contents )

io.close( file ) -- Important to close (python knowledge)

local t = display.newText( "Contents of ", 5, 80, nil, 16 ); -- w, h, ?, size
t:setFillColor( 1, 1, 135/255 ); -- edit
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setFillColor( 1, 1, 135/255 );

local ylast = 130 -- how far down the Y value it can make words on the screen
for line in io.lines(filePath) do
    local t = display.newText ( line, 15, ylast, nil, 14); -- dont understand
    t:setFillColor( 1, 1, 1 );
    ylast = ylast + 20
    end
end

local function inputListener( event )
if event.phase == "began" then

    -- user begins editing textBox
    print( event.text )

elseif event.phase == "ended" then
    textBox.text = event.text
    local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory )

    local file = io.open( path, "w" )
    file:write( textBox.text )
    io.close( file )
    file = nil 

elseif event.phase == "editing" then

    print( event.newCharacters )
    print( event.oldText )
    print( event.startPosition )
    print( event.text )

end
end

textBox:addEventListener( "userInput", inputListener )

【问题讨论】:

    标签: lua textbox coronasdk writing


    【解决方案1】:

    我建议使用 loadsave 功能,它会更容易。

    您可以从这里下载这些功能。

    https://github.com/robmiracle/Simple-Table-Load-Save-Functions-for-Corona-SDK

    下载后,只需将loadsave.lua 文件拖放到您的主项目文件夹中即可。

    现在你可以像这样使用它了。

    例子:

    local loadsave = require("loadsave")   
    
    local tableToSave = {}
    
    -- load text into a table
    tableToSave ['saved-text'] = textYouWantToSave
    
    -- save text
    loadsave.saveTable(tableToSave, "filename.json")
    
    local savedTable = {}
    
    -- load text
    savedTable = loadsave.loadTable("filename.json")
    
    -- text is stored here
    savedTable['saved-text']
    

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2017-04-11
      • 2017-05-01
      • 1970-01-01
      • 2022-12-15
      相关资源
      最近更新 更多