Cocos2d-x Lua reads Csv files for easier use of data, cocos2d-xcsv

Source: Internet
Author: User

Cocos2d-x Lua reads Csv files for easier use of data, cocos2d-xcsv


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 ~

 


How to combine cocos2d-x with Lua to use specific points

The cocos2d-x comes with the lua engine. Look at this. Although it is English, it is easy to understand.
Cocos2d-x NEW Lua Engine README
Main features
Support autorelease CCObject object.
Call Lua function from C ++ (local, global, closure), avoid memory leaks.
Add CCNode: setPosition (x, y), CCNode: getPosition () huge performance boost.
Remove needless class and functions from tolua ++. pkg files, improved performance.
CCMenuItem events handler.
CCNode onEnter/onExit events handler.
CCLayer touch & multi-touches events handler.
Check the two connections.
Www.cocos2d-x.org/..uments
Scripting and Translating between Programming ages

When creating a cocos2D-x project in VS2010, Select Lua support: Support Lua (Hook), an error is reported after generation,

Some library files are not properly loaded. Find the corresponding library file and paste it to the corresponding location. Do not forget to check whether the file has permissions.

Related Article

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.