Writing Files in GDScript

Here’s the translation of the Go code to GDScript, with explanations in Markdown format suitable for Hugo:

Writing files in GDScript follows similar patterns to the ones we saw earlier for reading.

extends Node

func _ready():
    # To start, here's how to dump a string (or just bytes) into a file.
    var content = "hello\nGodot\n"
    var file = File.new()
    var err = file.open("user://dat1", File.WRITE)
    if err == OK:
        file.store_string(content)
        file.close()
    else:
        print("Error opening file")

    # For more granular writes, open a file for writing.
    err = file.open("user://dat2", File.WRITE)
    if err == OK:
        # It's good practice to close the file when you're done with it.
        # In GDScript, we don't have defer, so we'll need to remember to close it manually.

        # You can write byte arrays as you'd expect.
        var d2 = PoolByteArray([115, 111, 109, 101, 10])
        file.store_buffer(d2)
        print("wrote %d bytes" % d2.size())

        # A store_string is also available.
        var n3 = file.store_string("writes\n")
        print("wrote %d bytes" % n3)

        # GDScript doesn't have a direct equivalent to Sync, 
        # but file operations are automatically flushed when the file is closed.

        # GDScript doesn't have a built-in buffered writer,
        # but you can implement your own if needed.

        file.close()
    else:
        print("Error opening file")

    # Try running the file-writing code.
    # Then check the contents of the written files in the user:// directory.
    # In Godot, user:// maps to a user-writable directory that depends on the platform.

# Next we'll look at applying some of the file I/O ideas
# we've just seen to the standard input and output streams.

To run this script, you would need to attach it to a Node in a Godot scene. The _ready() function will be called automatically when the scene is loaded.

Note that in GDScript, we use the File class for file operations. The user:// prefix is used to specify a user-writable directory, which is platform-dependent.

GDScript doesn’t have some of the features that Go has, such as defer for resource cleanup or built-in buffered writers. However, it provides similar functionality through its own methods and idioms.

Remember to handle errors appropriately in your actual code, as file operations can fail for various reasons.

查看推荐产品