Home Contents | # Save file management | Rawio | Core4 Lua Event System

## SYNOPSIS

1. state = rawio.newState(filename_pattern)
2. state:save(data)
3. table = state:restore()
4. string = state:load()

## DESCRIPTION

When saving data to a file on an embedded system there is always the chance that writing the file gets interrupted. A system should be robust against someone yanking out the power plug or even against the system crashing in the middle of the write.

This function will return a handler that can be used to manage file data with backup. The filename_pattern is the filename used for saving/restoring. It must contain a single '?' (question mark) character. Backup file management will replace this '?' with other characters to indicate which file is current and which is a backup.

When a state handler has been created, use state:save() to save a table or a string. The save function will take care that there is always a backup file present. So even when saving fails, a subsequent restore will simply restore the previous state.

To restore data, use state:restore() for a saved table and state:load() for arbitrary string data. The restore functions will first try to restore the last save, and, if this fails, try to restore from the backup file.

## RETURN VALUE

Returns a handler instance that can be used to save/restore data.

## EXAMPLE

This is an example for keeping state in a table. First the global state is initialized with defaults. Only if restore succeeds, the restored state is merged with the defaults. This makes sure that older saves, which might not have all fields present in the table, simply keep the defaults. Note that the file uses the extension ".lua", since table data is actually saved as proper Lua code.

> > > >
state = { data1 = "some data", data2 = "some other data" } sth = rawio.newState("/media/nv0/state?.lua") local restored_state = sth:restore() if (restored_state) then table.merge(state, restored_state) end

To save the state, simply do, this assumes the initialization code above has already run:

>
sth:save(state)

## SEE ALSO

table.tostring, table.fromstring