Cocos2d-x Lua reads CSV files for easier use of data

Source: Internet
Author: User


There is a CSV file shadow in my book or the source code I once sold.

Maybe it's preemptible. The longest configuration file I will use at work will be CSV, so I can't help but prioritize it in many games.

 

The CSV file is in a simple format, that is, a line of data, fields are separated by commas, planning can also be easily edited using Excel.

CSV files are easy to parse, so you can write them quickly ~ (Xiao RuO: I like it. What do you do)

 

I recently used Lua to write games. For skill and monster configurations, I still choose to use CSV ~

I have to say that Lua and other scripting languages are incomparable to C ++ in some aspects. This time I will use CSV to express this kind of mood ~

 

Stupid wood and flowers contribute, huh? Flowers? No, it's your heart ~

Reprinted please note, original address: http://www.benmutou.com/archives/1634

Source: dummies and Game Development

 

 

A csv configuration file

Let's take a look at this CSV file,

Bytes

(Xiao RuO: Is this a picture? Where is the image !)

 

Of course, it seems that this is not clear enough. Let's look at it like this:

This is a simple CSV file:

The first line is an English name, which is very important because we need to use this name in the code to obtain the corresponding field content.

The second line is a Chinese name, which does not have any effect. It is mainly for those who are reading, such as narration or something. (Xiao RuO: Do you want to be so specific ?)

The third and fourth rows are the actual content. Generally, I set the first field to ID, so that the content of the corresponding row can be easily obtained based on the ID.

 

Cocos code ide

OK, before reading the CSV file, a little mention of this IDE, it is an official Cocos2d-x IDE, specifically for Cocos2d-x + Lua, Cocos2d-x + JS, but does not support Cocos2d-x + C ++.

Although the current ide or RC version, I prefer early adopters, Cocos2d-x3.0 version I also from Alpha play ~

That's what I think ~

This article is based on Cocos code IDE, so I will mention it a little bit. IDE can download it from the official website and take a look at the Getting Started Guide for a few minutes.

Create a project.

 

String segmentation

After the project is created, the main. Lua and gamescene. Lua are created by default. We only need to perform a test in Main. Lua.

CSV is separated by commas. Therefore, the string splitting function is essential. Lua does not seem to provide this function. Fortunately, this is very simple.

 

Add a function before the main function in Mian. Lua:

function split(str, reps)    local resultStrsList = {};    string.gsub(str, ‘[^‘ .. reps ..‘]+‘, function(w) table.insert(resultStrsList, w) end );    return resultStrsList;end

Split has two parameters. STR is the string to be split, and reps is the separator ~

The gsub function of the string library is used here. There are three parameters in total:

1. STR, string to be split

2. '[^ '.. reps .. '] +', what is it, regular expression, I rarely use this product, so every time I use it, I will flip the document and forget it when I use it.

This is also relatively simple. For example, if reps is a comma, it becomes '[^,] +'. This expression means: searches for non-comma characters and matches them multiple times ~

For example, "heab,", the previous heab is not a comma, and all are matched until the fifth character is found. It is a comma and the matching is stopped, therefore, the final matching string is "heab ".

3. Each split string can be obtained through the callback function. The w parameter is a substring after the split and saved to a table.

OK, that's simple. In this way, we can get a table, which stores all the substrings to be split.

 

Test the function and delete the code of the default main function, as shown below:

local function main()    local t = split("nihfao,hehe,hen", ",");    for k, v in pairs(t) do        print(v);    endend


Then press F11 to output the following logs:

[LUA-print] nihfao

[LUA-print] hehe

[LUA-print] plugin

Succeeded ~

 

Real parsing CSV

The point is to parse the CSV file. We not only need to parse, parse, but also save it for later configuration data ~

Therefore, I thought of a good way to read data more conveniently in the future.

 

Let's look at the code and add a new function to the mian function:

Function loadcsvfile (filepath) -- reads the File Local Data = cc. fileutils: getinstance (): getstringfromfile (filepath); -- divide local linestr = Split (data, '\ n') by line '); -- [save from row 3rd (the first row is the title, the second row is the comment, and the following row is the content) with a two-dimensional array: arr [ID] [attribute title string] local titles = Split (linestr [1], ","); Local id = 1; Local arrs = {}; for I = 3, # linestr, 1 do -- the content of each column in a row is local content = Split (linestr [I], ","); -- the title is used as the index, save the content of each column. The value is as follows: arrs [1]. title arrs [ID] ={}; for j = 1, # titles, 1 do arrs [ID] [titles [J] = content [J]; end id = ID + 1; end return arrs; End

Is it easy? (Xiao RuO: simple wool !)

This is much simpler than parsing in C ++ ~


To analyze the sentence:

1. Read the file through the getstringfromfile function of fileutils and obtain the string content.

2. Local linestr = Split (data, '\ n'); Use the split function to split the file content by line to get a linestr, which stores the content of each row

3. Local titles = Split (linestr [1], ","); Do you still remember our CSV file? The first line of content is English letters, they are very important

Here, the content of the first line of the file is separated by commas to get titles, which stores every field in the first line.

What are the functions of these fields? In the future, we will use these fields to obtain configuration data.

4. Then, create a new table variable: Local arrs ={}; which will completely Save the parsed CSV file data.

5. There are two for loops.

First, let's look at the first loop:

For I = 3, # linestr, 1 do
-Content of each column in a row
Local content = Split (linestr [I], ",");

End

We have already said that the first line of CSV is an English field, the second line is a Chinese explanation, and the third line is the real content ~ So we need to start from the third line.

We know that the table subscript of Lua starts from 1, so the initial value of I is 3.

The content of each row is stored in linestr. Therefore, the for loop at the first layer is used to retrieve the content of each row, and then split it by commas to save it to the content variable.

 

Next, let's look at the Layer 2 loop:

-Use the title as an index to save the content of each column. When the value is set to this value, use arrs [1]. Title.

Arrs [ID] = {};
For j = 1, # titles, 1 do
Arrs [ID] [titles [J] = content [J];
End

What does arrs [ID] ={} mean? This indicates the content of a row. arrs [ID] can be viewed as an array, which stores the data of a row.

Then, the subscript of the arrs [ID] array is naturally our English letter (that is, the first line of content that has always been mentioned before ).

 

The logic is a bit messy, so we can understand it slowly:

Although content stores the content of each row, it does not obtain data because its subscript is a number.

Therefore, we need to copy the content one by one to the arrs [ID] and replace all the subscript numbers with English strings.

The second layer of the For Loop is doing this.

 


Test

Well, there must be some confusion in this explanation. Let's test it and you will know what I am talking about.

Modify the main function:

local function main()    local csvConfig = loadCsvFile("res/Mutou.Csv");        print(csvConfig[1].Name .. ":" .. csvConfig[1].Des);    print(csvConfig[2].Name .. ":" .. csvConfig[2].Des);end


Run F11 to output the following logs:

[LUA-print] advertisement: www.benmutou.com
[LUA-print] No: I won't add any advertisements.

 

First, loadcsvfile parses the CSV file and then returns the parsed content.

Next, I want to obtain the configuration data with ID 1. For example, to obtain its name field attribute, It is very simple: csvconfig [1]. Name ~

 

If you are unfamiliar with the Lua table, you may not be able to understand the "essence" of this article !)

For Lua's table, you can read my article. I believe you will have a preliminary understanding of table (enough to understand this article)

Some construction methods of table: http://www.benmutou.com/archives/627

 

Remarks

I personally think this is very convenient. I am not saying it is very convenient to parse it. Instead, it is very convenient to obtain the field value after parsing ~

If you want to add fields to the configuration file in the future, the parsing and usage will not be affected at all, which is the most comfortable place.

Of course, this requires that the first line of our configuration file cannot be written incorrectly, otherwise it will not be fun.

 

If it is in C ++, it may not be so convenient. Although it can also be imitated, it can be done through getvalue ("key ~

However, in any case, it is not as natural as a script ~

 

Although it is convenient, it is still uncomfortable to develop a full-script mobile game. In some cases, the script is not as efficient as C ++ (not the running efficiency )~

 

Okay, that's all ~ Don't hate me anymore ~

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.