Skip to content

New library: csv

dounai2333 edited this page Jan 4, 2025 · 3 revisions

Introduction

The csv library provides functions for reading .csv file and format to Lua table.

Example .csv file:

//the player level,message appear when level up,teleport player to this origin when they level up
Level,LevelUpMessage,Origin
int,string,vector
1,Newbie,0:0:0
2,You have level up!,50:0:0
3,"Congrats, you are now level 3!",50:50:0
4,"You are now level 4, keep fighting, warrior!", 100:100:100

Read:

local csv = dounai_lib.csv.Parse("test.csv")
print(IsValid(csv)) -- Output: "true"
print(csv:Length()) -- Output: "4"
print(#csv) -- Output: "3"

print(csv[2]) -- Output: "LevelUpMessage"
print(csv["LevelUpMessage"].type) -- Output: "string"
print(csv["LevelUpMessage"][3]) -- Output: "Congrats, you are now level 3!"

print(csv[csv[3]][4]) -- Output: "100.000000 100.000000 100.000000"

for k, v in ipairs(csv[csv[1]]) do
    print(v) -- Output: "1", "2", "3", "4"
end

Linq version:

local linqCsv = csv:ToLinq()
print(linqCsv:Length()) -- Output: "4"

for k, v in ipairs(linqCsv) do
    print(v:Get("Level")) -- Output: "1", "2", "3", "4"
end

Parse

dounai_lib.csv.Parse(path, gamemode_string)

Read and parse a .csv file, format it properly and save to a table.

BUG: If the csv file doesn't have the type line ("int" and "string" or so), or adding ";", "//" to the important line will cause exception!

You can use IsValid(csv) to check if the result is a valid csv table. csv:Length() will return the length of csv table.

If gamemode_string is given, then the priority of file will be:

-- First priority, example: scripts/mod/zombie/cs_assault/test.csv
scripts/mod/{gamemode_string}/(current map name)/{path}

-- Second priority, example: scripts/mod/zombie/test.csv
scripts/mod/{gamemode_string}/{path}

If gamemode_string is empty or nil, then the priority of file will be:

-- First priority, directly read the file from given path.
test.csv

-- Second priority, example: scripts/test.csv
scripts/test.csv

Return: table

path: string

gamemode_string: string

ToLinq

dounai_lib.csv.ToLinq(self)

Format the csv table to a for loop friendly table. See example above.

Return: table

self: table

Clone this wiki locally