Common Code Snippets Files

From GMod Wiki

Revision as of 04:16, 24 October 2010 by Assault Trooper (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Contents

Create a text file if doesn't already exist

This script will create the textfile if it doesn't exist.

 
local Textfile = "Example.txt"
 
if !file.Exists( Textfile ) then
 
file.Write( Textfile, "" )
 
end
 

How to Save a Table to a Text File

 
local savestring = util.TableToKeyValues(savetab)
file.Write("FilePath/Savedtab.txt",savestring)
 

Note: util.TableToKeyValues is deprecated. Use GLON instead.

How to Load a Table from a Text File

 
if(file.Exists("FilePath/Savedtab.txt")) then
   local readstring = file.Read("FilePath/Savedtab.txt")
   loadtab = util.KeyValuesToTable(readstring)
end
 

Note: util.KeyValuesToTable is deprecated. Use GLON instead.

Obtain the file and path of a script

This returns the filename and path of the script it is called from. All paths are relative to the virtual lua folder.

 
 
function GetScriptName( )
	return debug.getinfo( debug.getinfo( 2, "f" ).func ).short_src
end
 
function GetScriptPath( )
	// Get Name like above
	local Name = debug.getinfo( debug.getinfo( 2, "f" ).func ).short_src
 
	// Find the last forward slash (/) in the name	
	local Pos
	while true do 
		local NewPos = string.find( Name, "/", ( Pos or 0 ) + 1 )
		if not NewPos then break end
		Pos = NewPos
	end
 
	// If a forward slash was found, return all the text up to it	
	if Pos then
		return string.sub( Name, 1, Pos - 1 )
	// Otherwise, return nothing since the file is run at the root
	else
		return ""
	end
 
end
 
 
Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox